// The locales_home_accordion is a variable that determines which menu will be expanded in the homepage accordion. "1" equals first, "2" equals second, etc. Set as desired.
var locales_home_accordion = new Array ("en-us=1", "de-de=1", "en-gb=1", "es-es=1", "es-la=1", "fr-fr=1", "it-it=1", "ja-jp=1", "ko-kr=1", "pl-pl=1", "pt-br=1", "ru-ru=1", "tr-tr=1", "zh-cn=1", "zh-tw=1");
var exp_accordion = setOpenAccordion(locales_home_accordion);
if(HomepageFlashStruct){
swfobject.embedSWF(HomepageFlashStruct['data'][exp_accordion]['swf'], HomepageFlashStruct['id'], HomepageFlashStruct['width'], HomepageFlashStruct['height'], HomepageFlashStruct['version'], HomepageFlashStruct['express'], HomepageFlashStruct['data'][exp_accordion]['flashVars'], HomepageFlashStruct['data'][1]['params'], HomepageFlashStruct['data'][exp_accordion]['attributes']);
}

function addToCart(drid) {
	var quantity = $("#quantity" + drid).val();
	document.location = DR_addToCart_URL + '/productID.' + drid + '/quantity.' + quantity;
}
// Fix background image flickering in IE
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) { }

/* Special search behavior */
var Search = {
  prompt: "Search", // default value - should get real value from markup
  init: function() { this.prompt = jQuery('#search').focus(this.focus).blur(this.blur).val(); },
  focus: function() { if (this.value == Search.prompt) { this.value = ''; } },
  blur: function() { if (this.value.length == 0) { this.value = Search.prompt; } }
};

jQuery(function() {
  Search.init();
});
// Prevent Firebug debugging from breaking other browsers
// if (typeof console == "undefined") {
// 	console = {};
// 	console.dir = function() { return; };
// 	console.log = function() { return; };
// }

// Dialog container
var $dialog;

// Tabs container
var $tabs = null;

// Info about a product
var ProductInfoStruct;

// Default store id
var gblComStoreId;
if (gblComStoreId == null) {
	gblComStoreId = 'sgateus';
}

var gblComLocale;
if (gblComLocale == null) {
	gblComLocale = 'en_US';
}

// Query for product info
var DR_productInfo_URL = 'https://shop.seagate.com/store/'+gblComStoreId+'/'+gblComLocale+'/DisplayPage/id.DRProductInfoJSPage/content.price+buyLink+name+thumbnail+image+stockStatus+longDescription/output.json/jsonp.ProductInfoSelector.savePricingInfo/esiCaching.off';

// Base for building a URL to add things to the cart
var DR_addToCart_URL = 'https://shop.seagate.com/store/'+gblComStoreId+'/'+gblComLocale+'/AddItemToRequisition';

// Query the cart to determine how many items are in it
var DR_cartInfo_URL = 'https://shop.seagate.com/store/'+gblComStoreId+'/DisplayPage/id.DRCartSummaryJSONPage/output.json/jsonp.CartInfo.updateCartDisplay';

// var DR_pop_name = 'SiteMerchandising_SpecialOffersFeaturedProducts';
var DR_pop_name = 'SomeFallbackPopName';
if (	 ProductInfoStruct 
		&& ProductInfoStruct.releaseList
		&& jQuery.isArray(ProductInfoStruct.releaseList)
		&& ProductInfoStruct.releaseList.length > 0
		&& ProductInfoStruct.releaseList[0].releaseName)
{
	DR_pop_name = ProductInfoStruct.releaseList[0].releaseName;
}
var DR_popInfo_URL =  'https://shop.seagate.com/store/'+gblComStoreId+'/'+gblComLocale+'/DisplayPage/id.DROfferInfoJSPage/popName.' + DR_pop_name + '/output.json/jsonp.ProductInfoSelector.savePopInfo/productContent.displayName+shortDescription+price';

// Placeholder var for localized strings
var localeStrings;

// Placeholder var for homepage flash details
var HomepageFlashStruct;

// Populate display of how many items are in the cart
var CartInfo = {
	init: function() {
		if (gblComStoreId != null && gblComStoreId != "null") {
			jQuery.getScript(DR_cartInfo_URL);
		}
	},
	updateCartDisplay: function(arg) {
		$('#ShopInfo a.cart').text( localeStrings.cart + '[' + arg.lineItems + ' ' + localeStrings.items + ']');
	}
};

// Control images that are displayed for a product
var ProductShots = {
	currColor: '',
	selectedIndex: 0,
	productShots: [],
	flashData: null,
	flashModal: 'modals/flash_viewer.html',
	init: function() {
		var PS = ProductShots;
		//PS.productShots = $('.productShots');
		PS.productShots = $('div.heroContainer').siblings('div.productShots');
		if (PS.productShots.length == 0) return;

		var $lis = PS.productShots.find('ul.thumbnails li');
		PS.setupEvents($lis);
		var $selected = $lis.filter('.selected');
		if ($selected.length == 0) $selected = $lis;
		try{
			PS.select($selected[0]);
		}catch(e){
			alert(e);
		}
		if ($.fn.pngFix) {
			$('img#HeroImage').parent().pngFix();
		}
		
		if (DD_belatedPNG) {
			DD_belatedPNG.fix('div.productShots ul li.shadowed,div.productShots ul li.selected,div.productShots ul li img');
		}
		
	},
	setupEvents: function($lis) {
		$lis.hover(ProductShots.thumbOver, ProductShots.thumbOut).click(ProductShots.click);
	},
	thumbOver: function(event) {
		$(this).addClass('shadowed');
		var $shadowed_lis = $(this).siblings('.shadowed').removeClass('shadowed');
		if (DD_belatedPNG) {
			var el = this;
			setTimeout(function() { /* wouldn't work as intended without setTimeout */
				DD_belatedPNG.applyVML(el);
			}, 1);
			$shadowed_lis.each(function(i) {
				var elm = this;
				setTimeout(function() { /* wouldn't work as intended without setTimeout */
					DD_belatedPNG.applyVML(elm);
				}, 1);
			});
		}
	},
	thumbOut: function(event) {
		$(this).removeClass('shadowed');
		if (DD_belatedPNG) {
			var el = this;
			setTimeout(function() { /* wouldn't work as intended without setTimeout */
				DD_belatedPNG.applyVML(el);
			}, 1);
		}
	},
	showDialog: function() {
		var $div = $('#FlashPlayerModal');
		if ($div.length == 0)
			return;
		var flashData = ProductShots.flashData;
		if (! flashData)
			return;
			
		swfobject.embedSWF(flashData['swf'], 'ModalFlashContainer', flashData['width'], flashData['height'], flashData['version'], null, flashData['flashVars'], flashData['params'], flashData['attributes']);
		
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: parseInt(flashData['width']) + 32,
				// height: flashData['height'],
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');		
	},
	setupFlashPlayer: function() {
		$div = $('#FlashPlayerModal');
		if ($div.length == 0) {
			$div = $('<div id="FlashPlayerModal" style="display: none;"></div>').appendTo('body');
			$div.load(ProductShots.flashModal + ' div.modalContent', ProductShots.showDialog);
		} else {
			ProductShots.showDialog();
		}
	},
	click: function(event) {
		if ($(this).hasClass('flash')) {
			var model = ProductInfoSelector.currentModel();
			if (!model) return;
			// Assume that flash container is in last element of gallery struct
			var flashData = model.gallery[model.gallery.length - 1]['data'];
			if (!flashData) return;
			ProductShots.flashData = flashData;
			ProductShots.setupFlashPlayer();
		} else {
			ProductShots.select(this);
		}
	},
	select: function(elm) {
		
		var $selected_lis = $(elm).siblings('.selected') // li.selected
															.removeClass('selected');
		if (DD_belatedPNG) {
			$selected_lis.each(function(i) {
				var elm = this;
				setTimeout(function() { /* wouldn't work as intended without setTimeout */
					DD_belatedPNG.applyVML(elm);
				}, 1);
			});
		}
		
		$(elm).addClass('selected');
					
		var $children = $(elm).parent().children();
		for (var i=0, length = $children.length; i<length; i++) {
			if ($($children[i]).html() == $(elm).html()) {
				ProductShots.selectedIndex = i;
				break;
			}
		}

		// Convert src from thumb to hero image
		var src = $(elm).find('img').attr('src');
		src = src.replace(/67x59/,'320x340');

		var currSrc = $('#HeroImage').attr('src');
		if (currSrc != src) {
			$('#HeroImage').attr('src', src);
			if ($.fn.pngFix) {
				// Re-run png fix whenever we switch images because the image changes.
				$('img#HeroImage').parent().pngFix();
			}
		}
	},
	
	// TODO - add support for additional types
	buildThumbnail: function(obj) {
		if (obj.type == 'image') {
			return '<li><img src="' + obj.src + '" width="67" height="59" alt="' + obj['alt'] + '"/></li>';
		} else if (obj.type == 'flash') {
			return '<li class="flash"><img src="' + obj.src + '" width="67" height="59 alt="' + obj['alt'] + '"/></li>';
		}
		return null;
	},
	showModel: function(model) {
		if (! model || ! model.gallery) {
			// alert("invalid model");
			return;
		}
		var PS = ProductShots;
		PS.productShots = $('.productShots');
		if (PS.productShots.length == 0) return;
		if (model.color != PS.currColor) {
			var oldColor = ProductShots.currColor;
			PS.currColor = model.color;
			var $ul = PS.productShots.find('ul.thumbnails').html('');
			for (var i = 0, length = model.gallery.length; i<length; i++) {
				$ul.append(PS.buildThumbnail(model.gallery[i]));
			}
			var $children = $ul.children();
			if (PS.selectedIndex >= $children.length)
				PS.selectedIndex = 0;
			PS.select($children[PS.selectedIndex]);
			PS.setupEvents($children);
		}
	}
};

var Toolbar = {
	init: function() {
		$('#Toolbar li.menu').hover( Toolbar.toggleOn, Toolbar.toggleOff );
	},
	toggleOn: function(e) {
		e.preventDefault();
		$(this).addClass('active');
		if ($.fn.bgiframe)
			$(this).children('ul:first').bgiframe();
	},
	toggleOff: function(e) {
		e.preventDefault();
		$(this).removeClass('active');		
	}
};

var SectionInfoBlock = {
	init: function () {
		var expanded = 0;
		expanded = setOpenAccordion(locales_home_accordion);
		if ($.fn.accordion) {
			$('.sectionInfoBlock .accordion').accordion(
					{
						active: expanded,
						header: 'h2',
						change: function(event, ui) {
							$('.sectionInfoBlock .accordion h2').each(function(i,h) {
								if ($(h).text() == ui.newHeader.text()) {
									SectionInfoBlock.changeSWF(i);
									return false;
								}
							});
							if ($.fn.pngFix) {
								// Re-run png fix whenever we switch content because the background image changes.
								ui.newHeader.parent().pngFix();
								ui.oldHeader.parent().pngFix();
								ui.newContent.find('> a').show();
							}
						},
						changestart: function(event, ui) {
							if ($.fn.pngFix) { // hook for IE6 only
								ui.newContent.find('> a').hide();
							}
						}
					}
			);
			if ($.fn.pngFix) {
				$('div.sectionInfoBlock .accordion li').pngFix();
			}
		}
	},
	changeSWF: function(i) {
		if (HomepageFlashStruct) {
			var $flash_parent = $('#' + HomepageFlashStruct['id']).parent();
			swfobject.removeSWF(HomepageFlashStruct['id']);
			$flash_parent.prepend('<div id="' + HomepageFlashStruct['id'] + '"></div>');
			swfobject.embedSWF(HomepageFlashStruct['data'][i]['swf'], HomepageFlashStruct['id'], HomepageFlashStruct['width'], HomepageFlashStruct['height'], HomepageFlashStruct['version'], null, HomepageFlashStruct['data'][i]['flashVars'], HomepageFlashStruct['data'][i]['params'], HomepageFlashStruct['data'][i]['attributes']);					
		}
	}
};

// IE6 alpha PNG support
// http://www.dillerdesign.com/experiment/DD_belatedPNG/
var DD_belatedPNG;
if (DD_belatedPNG) {
  DD_belatedPNG.fix('div.promo .header,div.promo .footer,li.icon,li.active #Login .content a,#Mast #HeroImage');
	DD_belatedPNG.fix('ul#NavigationPrimary li div.channel ul.buttons li a,ul#NavigationPrimary li div.channel ul.buttons li a span');
	DD_belatedPNG.fix('a.shop,a.highlightButton,a.highlightButton span,a.highlightButtonSmall,a.highlightButtonSmall span,a.highlightButtonMedium,a.highlightButtonMedium span');
	DD_belatedPNG.fix('div.promoCarousel a.jcarousel-prev,div.promoCarousel a.jcarousel-next');
	DD_belatedPNG.fix('ul.releaseList img,#FlashBanner img,#News,div.sectionInfoBlock,div.quickLinks ul li');
}

// Handle user picking colors.
var ColorPicker = {
	selectedColor: '',
	pickers: [],
	colorLookup: { },
	init: function(colors) {
		var CP = ColorPicker;
		var $pickers = CP.pickers = $('.colorPicker');
		if ($pickers.length == 0) {
			CP.selectedColor = 'no_color';
			return false;
		}

		$pickers.children('ul').addClass('pretty selfClear').children().each( function (i) {
			var $li = $(this);

			var $img = $li.children('img:first');
			if ($img.length != 1) return;

			var $input = $li.children('input:first');
			if ($input.length != 1) return;
			var color = $input.val();

			$input.replaceWith(''); // faster than .remove()

			// Using data function is slow
			CP.storeColor(color, $img);
			// $img.data('color_value', color);

			if (jQuery.inArray(color, colors) < 0)
				$li.hide();

			if ($li.hasClass('selected'))
				CP.selectedColor = CP.retrieveColor($img);

			$li.hover(CP.over, CP.out).click(CP.click).height($img.height() + 'px');

			CP.defaultColor(CP.selectedColor);
		});
	},
	updateColors: function(colors) {
		var C = ColorPicker;
		C.pickers.find('ul li').each( function(i) {
			var $li = $(this);
			var $img = $li.find('img');
			var color = C.retrieveColor($img);
			if (jQuery.inArray(color, colors) > -1) {
				$li.show();
			} else if ($li.is(':visible')) {
				$li.hide();
				if ($li.hasClass('selected')) {
					$li.removeClass('selected');
				}
			}
		});

		// If no color is selected, select the first one.
		var $selectedColor = C.pickers.find('li.selected:visible');
		// console.log('$selectedColor');
		// console.dir($selectedColor);
		if ($selectedColor.length == 0) {
			var dont_track_selector_update = true;
			C.handleClick(C.pickers.find('ul li:visible:eq(0)'), dont_track_selector_update);
		}
	},
	defaultColor: function(colors) {
		var C = ColorPicker;
		// If no color is selected, select the first one.
		//var $selectedColor = C.pickers.find('li.selected:visible');
		// console.log('$selectedColor');
		// console.dir($selectedColor);
		//if ($selectedColor.length == 0) {
			var dont_track_selector_update = true;
			C.handleClick(C.pickers.find('ul li:visible:eq(0)'), dont_track_selector_update);
		//}
	},
	resetColors: function(colors) {
		var C = ColorPicker;
		C.pickers.find('ul li').each( function(i) {
			var $li = $(this);
			var $img = $li.find('img');
			var color = C.retrieveColor($img);
			if (jQuery.inArray(color, colors) > -1) {
				$li.show();
			} else if ($li.is(':visible')) {
				$li.hide();
				if ($li.hasClass('selected')) {
					$li.removeClass('selected');
				}
			}
		});

		// If no color is selected, select the first one.
		//var $selectedColor = C.pickers.find('li.selected:visible');
		// console.log('$selectedColor');
		// console.dir($selectedColor);
		//if ($selectedColor.length == 0) {
			var dont_track_selector_update = true;
			C.handleClick(C.pickers.find('ul li:visible:eq(0)'), dont_track_selector_update);
		//}
	},
	selectColor: function(color) {
		var $img = ColorPicker.getImageForColor(color);
		if (!jQuery.isArray($img) || $img.length == 0) return;
		ColorPicker.handleClick($img.parent(), false);
	},
	storeColor: function(color, $img) {
		ColorPicker.colorLookup[$img.attr('src')] = color;
	},
	retrieveColor: function($img) {
		return ColorPicker.colorLookup[$img.attr('src')];
	},
	getImageForColor: function(color) {
		var CP = ColorPicker;
		for (imgSrc in CP.colorLookup) {
			if (CP.colorLookup[imgSrc] == color) {
				return CP.pickers.find("img[src*='" + imgSrc + "']");
			}
		}
	},
	over: function(event) {
		$(this).addClass('over');
	},
	out: function(event) {
		$(this).removeClass('over');
	},
	click: function(event) {
		event.preventDefault();
		ColorPicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		// console.log("handleClick");
		var $img =
			$(li)	.parents('ul:0') // Containing UL
							.find('li.selected') // selected LI s
							.removeClass('selected') // unselect them
							.end().end() // back to "this"
							.addClass('selected') // select it
							.find('img'); // get the image
		ColorPicker.selectedColor = ColorPicker.retrieveColor($img);

		ProductInfoSelector.colorChanged( ColorPicker.selectedColor, $(li).find('img').attr('alt'), dont_track_selector_update );
		ProductShots.showModel( ProductInfoSelector.currentModel() );
	},
	handleClickForColor: function(color) {
		var C = ColorPicker;
		C.handleClick(C.liForColor(color));
	},
	liForColor: function(color) {
		var ret = null;
		ColorPicker.pickers.find('li img').each( function(i) {
			if (ColorPicker.retrieveColor($(this)) == color) {
				ret = $(this).parent();
				return; // break;
			}
		});
		return ret;
	}
	
};

// Control product info dropdowns and add to cart button
var ProductInfoSelector = {
	color: null,
	capacity: null,
	'interface': null,
	cache: null,
	product: null,
	sku: null,
	releaseIndex: 0,
	modelIndex: 0,
	changeField: null,
	defaultSubtitle: null,
	subtitleElm: null,
	
	init: function() {
		if (! ProductInfoStruct)
			return false;
		
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		P.color = ColorPicker.selectedColor;
		
		var $container = $('div.productInfoSelector');
		var $subtitle = $container.siblings('h2');
		if ($subtitle.length > 0) {
			P.defaultSubtitle = $subtitle.text();
			P.subtitleElm = $subtitle;
			
		}
		var modelList = P.currentModelList();
		
		ColorPicker.init(P.colorList(modelList));
		//ColorPicker.resetColors(P.colorList(modelList));
		
		P.updatePulldowns(modelList);
		// P.capacity = 
		$container.find('select[name=capacity]').change(P.capacityChanged).val();
		// P['interface'] = 
		$container.find('select[name=interface]').change(P.interfaceChanged).val();
		// P.cache = 
		$container.find('select[name=cache]').change(P.cacheChanged).val();
		$container	.siblings('div.purchaseContainer')
								.find('input[name=quantity]')
								.keyup(P.quantityChanged)
								.addClass('changeEvent');

		$container.find('a.reset').click(P.resetChoices);
		//ColorPicker.defaultColor(P.colorList(modelList));
	},
	resetChoices: function(event) {
		event.preventDefault();
		var P = ProductInfoSelector;
		P.color = P.capacity = P['interface'] = P.cache = null;
		P.changeField = null;
		var modelList = P.currentModelList();
		ColorPicker.updateColors(P.colorList(modelList));
		ColorPicker.defaultColor(P.colorList(modelList));
		P.updatePulldowns(modelList);
		//P.resetCapacitySelector(modelList);
		//alert("Test Please Ignore");
	},
	productIDStringForAllModels: function() {
		if (! ProductInfoStruct)
			return false;
		
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		var modelList = P.fullModelList();
		var drIdList = P.drIdList(modelList);
		return jQuery.map(drIdList, function(n, i) { if (n != 0) {return ('/productID.' + n);} }).join('');		
	},
	setupPricingInfo: function() {
		var P = ProductInfoSelector;
		if (gblComStoreId != null && gblComStoreId != "null") {
			var productID_str = P.productIDStringForAllModels();
			if (productID_str == false) 
				return false;
			jQuery.getScript(DR_productInfo_URL + productID_str);
			
		}
	},
	savePricingInfo: function(product_arg) {
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		var products_list = [];
		if (jQuery.isArray(product_arg))
			products_list = product_arg;
		else
			products_list.push(product_arg);

		OUTER:
		for (var i=0, length = I.releaseList[P.releaseIndex].modelList.length; i < length; i++) {
			
			for (var j=0, products_list_length = products_list.length; j < products_list_length; j++) {
				if (I.releaseList[P.releaseIndex].modelList[i].drProductId === products_list[j].productID) {
					I.releaseList[P.releaseIndex].modelList[i].drInfo = products_list[j];
					if (products_list[j]['error']) {
						// Defaults for an error product to not show a price or order info
						I.releaseList[P.releaseIndex].modelList[i].drInfo.price = { discounted: false, unitPrice: '' };
						I.releaseList[P.releaseIndex].modelList[i].drInfo.stockStatus = localeStrings.DR_outofstock;
					}
					continue OUTER;
				}
			}
		}
		P.updateSKU(); //update the default model price after info is loaded
	},
	setupPopInfo: function() {
		var P = ProductInfoSelector;
		
		if (gblComStoreId != null && gblComStoreId != "null") {
			var productID_str = P.productIDStringForAllModels();
			if (productID_str == false) 
				return false;
				
			jQuery.getScript(DR_popInfo_URL + productID_str);	
		}
	},
	savePopInfo: function(pop_arg) {
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		var offer_instance_list = [];
		
		if (	 pop_arg
				&& pop_arg.offerInfo 
				&& pop_arg.offerInfo.offerInstances 
				&& pop_arg.offerInfo.offerInstances.offerInstance
		) {
			offer_instance_list = pop_arg.offerInfo.offerInstances.offerInstance;
		}	else
				return false;
			
		if (!jQuery.isArray(offer_instance_list))
			offer_instance_list = [ offer_instance_list ];
			
		for (var i=0, length=I.releaseList[P.releaseIndex].modelList.length; i < length; i++) {
			if (!(I.releaseList[P.releaseIndex].modelList[i].drOfferInfo)) {
				I.releaseList[P.releaseIndex].modelList[i].drOfferInfo = [];
			}
			for (var j=0, offer_instance_list_length = offer_instance_list.length; j < offer_instance_list_length; j++) {
				var offer_instance = offer_instance_list[j];
				if (offer_instance) {
					var offer_product_instances = offer_instance['offerProductInstances'];
					if (offer_product_instances['offerProductInstance']) {
						offer_product_instances = offer_product_instances['offerProductInstance'];
					}
					if (!jQuery.isArray(offer_product_instances))
						offer_product_instances = [ offer_product_instances ];
					for (var k=0, offer_product_instances_length = offer_product_instances.length; k < offer_product_instances_length; k++) {
						if (! offer_product_instances[k])
							continue;
						var offer_product_instance = offer_product_instances[k];
						if (	 offer_product_instance
								&& offer_product_instance.product
								&& offer_product_instance.product.productID
								&& offer_product_instance.product.productID 
										== I.releaseList[P.releaseIndex].modelList[i].drProductId
						) {
							I.releaseList[P.releaseIndex].modelList[i].drOfferInfo.push(offer_instance);
						}
					}
				}
			}
		}
		setTimeout("ProductInfoSelector.updateSKU()", 500); // Need a delay for proper cross-browser implementation
		P.updateFields();
	},
	fullModelList: function() {
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;

		var modelList = [];
		if (
				I.releaseList && jQuery.isArray(I.releaseList) && I.releaseList.length > this.releaseIndex 
					&& I.releaseList[this.releaseIndex].modelList 
					&& jQuery.isArray(I.releaseList[this.releaseIndex].modelList)
				)
		{
			modelList = I.releaseList[this.releaseIndex].modelList;
		}
		return modelList;
	},
	currentModelList: function() {
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;

		var modelList = [];
		if (
				I.releaseList && jQuery.isArray(I.releaseList) && I.releaseList.length > this.releaseIndex 
					&& I.releaseList[this.releaseIndex].modelList 
					&& jQuery.isArray(I.releaseList[this.releaseIndex].modelList)
					&& I.releaseList[this.releaseIndex].modelList.length > this.modelIndex
				)
		{
			modelList = P.filterModelList(
										I.releaseList[this.releaseIndex].modelList,
										P.buildModelFilter()
									);
		}
		return modelList;		
	},
	colorList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n.color); });
	},
	capacityList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n.capacity); });		
	},
	interfaceList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n['interface']); });		
	},
	cacheList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n.cache); });		
	},
	drIdList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n.drProductId); });		
	},
	filterModelList: function(modelList, filterArgs) {
		var ret = [];
		OUTER:
			for (var i = 0, length = modelList.length; i < length; i++) {
				for (var prop in filterArgs) {
					if (! (modelList[i][prop] && modelList[i][prop] == filterArgs[prop]))
						continue OUTER;
				}
				ret.push(modelList[i]);
			}
		return ret;
	},
	buildModelFilter: function() {
		var filter = {};
		var args = [ 'color', 'capacity', 'interface', 'cache' ];
		for (var i = 0, length = args.length; i < length; i++) {
			if (ProductInfoSelector[args[i]]) {
				// console.log("%s: %s", args[i], ProductInfoSelector[args[i]]);
				filter[args[i]] = ProductInfoSelector[args[i]];
			}
		}
		return filter;
	},
	updateCapacitySelector: function(modelList) {
		var P = ProductInfoSelector;
		// Don't update if this is what initiated the changes.
		
		if (P.changeField == 'capacity') {
			var model = P.currentModel();
			model && P.updateCapacityText(model.capacity, true);
		} else {
			var $select = $('select[name=capacity]')
										.find('option')
										.each(function(i) {
											// Always remove option 0 because if we build an array of indexes
											// we're chasing a moving target because as each one is removed
											// it affects the index numbering
											//alert($(this).val());
											$(this).parent().removeOption(0);
										})
										.end()
										.addOption(
											arrToObj(P.capacityList(modelList)),
											false
										);
		if (P.capacity)
			$select.selectOptions(P.capacity);
		else {
			var model = P.currentModel();
		 	model && P.updateCapacityText(model.capacity, true);
		}
		}
	},
	resetCapacitySelector: function(modelList) {
		var P = ProductInfoSelector;
		var lclcount=1;
		var $select = $('select[name=capacity]')
										.find('option')
										.each(function(i) {
											// Always remove option 0 because if we build an array of indexes
											// we're chasing a moving target because as each one is removed
											// it affects the index numbering
											//alert($(this).val());
											$(this).parent().removeOption(0);
										})
										.end()
										.addOption(
											arrToObj(P.capacityList(modelList)),
											false
										)
										.each(function(jk) {
											// Always remove option 0 because if we build an array of indexes
											// we're chasing a moving target because as each one is removed
											// it affects the index numbering
											if (lclcount=1) {
												P.capacity = $(this).val();
											}//alert($(this).val());
											lclcount=0;
										});
		//alert(P.capacity);
		if (P.capacity)
			$select.selectOptions(P.capacity);
		else {
			var model = P.currentModel();
		 	model && P.updateCapacityText(model.capacity, true);
		}
	},
	updateInterfaceSelector: function(modelList) {
		var P = ProductInfoSelector;
		// Don't update if this is what initiated the changes.
		if (P.changeField == 'interface')
			return;
			
		var $select = $('select[name=interface]')
										.find('option')
										.each(function(i) {
											// Always remove option 0 because if we build an array of indexes
											// we're chasing a moving target because as each one is removed
											// it affects the index numbering
											$(this).parent().removeOption(0);
										})
										.end()
										.addOption(
											arrToObj(P.interfaceList(modelList)),
											false
										);
		if (P['interface'])
			$select.selectOptions(P['interface']);
		else {
			var model = P.currentModel();
		 	model && P.updateInterfaceText(model['interface'], true);
		}
	},
	updateCacheSelector: function(modelList) {
		var P = ProductInfoSelector;
		// Don't update if this is what initiated the changes.
		if (P.changeField == 'cache')
			return;
		var $select = $('select[name=cache]')
										.find('option')
										.each(function(i) {
											// Always remove option 0 because if we build an array of indexes
											// we're chasing a moving target because as each one is removed
											// it affects the index numbering
											$(this).parent().removeOption(0);
										})
										.end()
										.addOption(
											arrToObj(P.cacheList(modelList)),
											false
										);
		if (P.cache)
			$select.selectOptions(P.cache);
		else {
			var model = P.currentModel();
		 	model && P.updateCacheText(model.cache, true);
		}
	},
	colorChanged: function(color, pretty_name, dont_track_selector_update) {
		// console.log('colorChanged');
		var P = ProductInfoSelector;
		// console.log("dont_track_selector_update:", dont_track_selector_update);
		if (! dont_track_selector_update) {
			P.color = color;
			P.changeField = 'color';
		}
		$('#ProductColor').text(pretty_name);
		P.updateSKU();
		if (! dont_track_selector_update)
			P.updatePulldowns();
		// Analytics hook
	},
	capacityChanged: function(event) {
		// console.log('capacityChanged');
		event.preventDefault;
		var P = ProductInfoSelector;
		P.changeField = 'capacity';
		P.capacity = $(this).val();
		P.updateCapacityText(P.capacity);
		
		P.updateSKU();
		P.updateFields();
		// Analytics hook
	},
	comparison: function()
    {
        var P = ProductInfoSelector;
        var model = P.currentModel();
        if (!model)
            return;
        P.sku = model.modelNumber;
        var options = new Object();
        options.widgetConfigurationId = '1661cebc-3fd3-444a-99eb-2a03c6f655ba';
        //options.container = _ps_GetContainer(options.widgetConfigurationId);
        options.container = document.getElementById('PricespiderWhereToBuyPopupButtonContainerDiv');
        if (gblLocale != null)
        {
            if (gblLocale == "en-US")
            {
                options.sku = "US_" + P.sku;
            } else if (gblLocale == "en-GB")
            {
                options.sku = "UK_" + P.sku;
            } else if (gblLocale == "fr-FR")
            {
            	options.popupContainerCloseButtonStyle = 'ps_PopupContainerCloseButtonFRStyle';
            	options.sku = "FR_" + P.sku;
            	options.language='FR';
            } else if (gblLocale == "de-DE")
            {
            	options.popupContainerCloseButtonStyle = 'ps_PopupContainerCloseButtonDEStyle';
            	options.sku = "DE_" + P.sku;
            } else {
            	return; //don't continue for other locales
            }
        }
 
        if (document._ps_wtb)
        {
            var widget = _ps_FindWidgetInfo(document._ps_wtb);
            if (widget && widget.sku != options.sku)
            {
                ps_Clear(document._ps_wtb);
                document._ps_wtb = ps_Show(options);
            }
            else if (widget == undefined || widget == null)
            {
                document._ps_wtb = ps_Show(options);
            }
        }
        else
            document._ps_wtb = ps_Show(options);
    },
	updateCapacityText: function(text, changeSelect) {
		$('#ProductCapacity').text(text);
		if (changeSelect)
			$('select[name=capacity]').selectOptions(text);
	},
	interfaceChanged: function(event) {
		// console.log('interfaceChanged');
		event.preventDefault;
		var P = ProductInfoSelector;
		P.changeField = 'interface';
		P['interface'] = $(this).val();
		P.updateInterfaceText(P['interface']);
		P.updateSKU();
		P.updateFields();
		// Analytics Hook
	},
	updateInterfaceText: function(text, changeSelect) {
		$('#ProductInterface').text(text);
		if (changeSelect)
			$('select[name=interface]').selectOptions(text);
	},
	quantityChanged: function(event) {
		// console.log('qualityChanged');
		ProductInfoSelector.updateBuyLink();
	},
	cacheChanged: function(event) {
		// console.log('cacheChanged');
		event.preventDefault;
		var P = ProductInfoSelector;
		P.changeField = 'cache';
		P['cache'] = $(this).val();
		P.updateCacheText(P['cache']);
		P.updateSKU();
		P.updateFields();
		// Analytics Hook
	},
	updateCacheText: function(text, changeSelect) {
		$('#ProductCache').text(text);
		if (changeSelect)
			$('select[name=cache]').selectOptions(text);
	},
	updateFields: function(modelListArg) {
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		var modelList = modelListArg || P.currentModelList();

		P.updateColor(modelList);
		P.updatePulldowns(modelList);
	},
	currentModel: function() {
		var modelList = ProductInfoSelector.currentModelList();
		var model = null;
		if (jQuery.isArray(modelList) && modelList.length > 0)
			model = modelList[0];
		return model;
	},
	normalizeStockStatus: function(model) {
		var stockStatus = model.drInfo.stockStatus;
		// console.log('stockStatus: %s', stockStatus);
		if (! stockStatus)
			return '';
		if (stockStatus == localeStrings.DR_preorder) {
			return 'preorder';
		}
		if (stockStatus == localeStrings.DR_instock) {
			return 'instock';
		}
		if (stockStatus == localeStrings.DR_outofstock && model.backorderable) {
			return 'backorder';
		}
		if (stockStatus == localeStrings.DR_outofstock) {
			return 'outofstock';
		}
	},
	getBuyTextFromStockStatus: function(model) {
		var stockStatus = this.normalizeStockStatus(model);
		
		switch(stockStatus) {
			case 'preorder':
				return localeStrings.SG_preorder;
			case 'instock':
				return localeStrings.SG_instock;
			case 'backorder':
				return localeStrings.SG_backorder;
			case 'outofstock':
				return localeStrings.SG_outofstock;
		}
		return '';
	},
	getStockStatusTextFromStockStatus: function(model) {
		var stockStatus = this.normalizeStockStatus(model);
		
		switch(stockStatus) {
			case 'preorder':
				return localeStrings.SG_preorder_description;
			case 'instock':
				return localeStrings.SG_instock_description;
			case 'backorder':
				return localeStrings.SG_backorder_description;
			case 'outofstock':
				return localeStrings.SG_outofstock_description;
		}
		return '';		
	},
	// TODO - refactor - this updates price info too
	updateSKU: function() {
		
		// console.log("updateSKU");
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		
		var model = P.currentModel();
		if (! model)
			return;

		//alert(model.modelNumber);
		// console.dir(model);
		P.sku = model.modelNumber;
		
		if (P.sku) {
			$('#ProductSKU').text(P.sku);
			// changeModel(P.sku);
		}
		
		P.updateTabLinks();
		P.comparison(); //update price spider widget parameters
		
		if (! model.drInfo) {
			
			//var $pc = $('div.productInfoSelector').siblings('div.purchaseContainer');
			/*var $pc = $('div.productInfoSelector')
									.siblings('div.focusBoxContainer')
									.children('.purchaseContainer');*/
									var $pc=$("#focusBoxContainer_purchaseContainer_001");
					//alert($("#focusBoxContainer_purchaseContainer_001").length);				
			if ($pc.length > 0) {
				var model = ProductInfoSelector.currentModel();
				/*$pc.find('div.addCart').hide();
				$pc.find('p.price').hide();
				$pc.find('p.stock').hide();*/
				//alert("parent"+$pc.parent());
				$pc.parent().addClass('focusBoxContainerRight');
			}	
			return;
		}
		
		
		//var $pc = $('div.productInfoSelector').siblings('div.purchaseContainer');

		/*var $pc = $('div.productInfoSelector')
								.siblings('div.focusBoxContainer')
								.children('.purchaseContainer');*/
				var $pc=$("#focusBoxContainer_purchaseContainer_001");
			
		if(typeof(model.drInfo.error) == "undefined"){
			
			if ($pc.length > 0) {
				$pc.parent().removeClass('focusBoxContainerRight');
				if (P.subtitleElm != null) {
					
							if (model.subtitle){
								//P.subtitleElm.text(model.subtitle);
								document.getElementById("h2_info_id").innerHTML=model.subtitle;
							}else{
								//P.subtitleElm.text(P.defaultSubtitle);
								
								document.getElementById("h2_info_id").innerHTML=P.defaultSubtitle;
							}
						}
				
				var price = model.drInfo.price;
				if (price.discounted) {
					$pc.find('p.price').addClass('onSale').html('<em class="regular">' + localeStrings.regular + price.unitPrice + '</em> <em class="sale">' + localeStrings.sale + price.unitPriceWithDiscount + '</em>');
				} else {
					$pc.find('p.price').removeClass('onSale').html(price.unitPrice);
				}
				/*P.updateBuyLink();
				$pc	.find('p.special') // We may have a "special" class...
						.replaceWith('')   // ...which we don't need
						.end()	// back to $pc
						.find('p[class=]') // paragraphs without classes
						.replaceWith('') // delete them
						.end() // back to $pc
						.find('p.price') // price display
						.after( // insert the content after the element
							jQuery.map( model.drOfferInfo || [], function(n, i) {
								// Convert offerInstances to offer text
								return P.getOfferTextFromOfferInstance(n);
							}).join('') // merge the list for insertion
						);*/
				P.updateBuyLink();
				
				$pc	.find('p[class=]') // paragraphs without classes
						.replaceWith('') // delete them
						.end() // back to $pc
						.find('p.special') // We may have a "special" class...
						.replaceWith('')   // ...which we don't need
						.end()	// back to $pc
						.find('p.stock') // price display
						.after( // insert the content after the element
							jQuery.map( model.drOfferInfo || [], function(n, i) {
								// Convert offerInstances to offer text
								return P.getOfferTextFromOfferInstance(n);
							}).join('') // merge the list for insertion
						);
						
				
			}
		}
	},
	getOfferTextFromOfferInstance: function(offerInstance) {
		if (! offerInstance)
			return '';
		
		if (offerInstance.salesPitchKey1) {
			//return '<p>' + offerInstance.salesPitchKey1 + '</p>';
			return '<p class="special">' + offerInstance.salesPitchKey1 + '</p>';
		}
		
		return '';
	},
	updateBuyLink: function() {
		// console.log("updateBuyLink");
		//var $pc = $('div.productInfoSelector').siblings('div.purchaseContainer');
		/*var $pc = $('div.productInfoSelector')
								.siblings('div.focusBoxContainer')
								.children('.purchaseContainer');*/
								var $pc=$("#focusBoxContainer_purchaseContainer_001");
		if ($pc.length > 0) {
			var model = ProductInfoSelector.currentModel();
			if (! model)
				return;
			var buttonText = ProductInfoSelector.getBuyTextFromStockStatus(model);
			// console.log('buttonText: %s', buttonText);
			
			if (buttonText) {
				$pc.find('div.addCart').show()
						.find('a.focusButton').attr('href', DR_addToCart_URL + '/productID.' + model.drProductId + '/quantity.' + $pc.find('input[name=quantity]').val()).find('span em').text(buttonText);
				//$pc.find('p.price').show();
				$pc.parent().removeClass('focusBoxContainerRight');
			} else {
				$pc.parent().addClass('focusBoxContainerRight');
				//$pc.find('div.addCart').hide();
				//$pc.find('p.price').hide();
			}
			var stockStatusText = ProductInfoSelector.getStockStatusTextFromStockStatus(model);
			if (stockStatusText) {
				$pc.find('p.stock').text(stockStatusText).show();
			} else {
				$pc.find('p.stock').hide();
			}
		}
	},

	updateColor: function(modelListArg) {
		var P = ProductInfoSelector;
		// Don't update if this is what initiated the changes.
		if (P.changeField == 'color')
			return;
		var modelList = modelListArg || P.currentModelList();
		
		ColorPicker.updateColors(P.colorList(modelList));
		
		var model = P.currentModel();
		if (model) {
			ColorPicker.selectColor(model.color);
		}
	},
	updatePulldowns: function(modelListArg) {
		var P = ProductInfoSelector;
		var modelList = modelListArg || P.currentModelList();
		
		// console.log('modelList');
		// console.dir(modelList);

		P.updateCapacitySelector(modelList);
		P.updateInterfaceSelector(modelList);
		P.updateCacheSelector(modelList);

	},

	updateTabLinks: function() {
		if (! $tabs) return false;
		var P = ProductInfoSelector;
		for (var i = 0; i < $tabs.tabs('length'); i++) {
			var $a = $tabs.find('ul.tabNav li:eq(' + i + ') a.modelSpecific');
			if ($a.length > 0)
				$tabs.tabs('url', i, P.buildURL($a.attr("id")));
			if ( ($a.parent('li.ui-state-active')).length > 0)
				$tabs.tabs('load', i);
		}
	},
	buildURL: function(tabName) {
		var P = ProductInfoSelector;
		if (tabName == "supportTab") {
			return '/ww/templates/retail/products/overrides/supportTab.jsp?modelNum='+ P.sku + '&locale=' + gblLocale;
		} else if (tabName == "specificationsTab") {
			return '/ww/templates/retail/products/overrides/specTab.jsp?modelNum='+ P.sku + '&locale=' + gblLocale;
		}
	}
};

var ProductFinder = {
	index: 0,
	init: function() {
		$('a.productFinder').click(ProductFinder.click);
	},
	showDialog: function() {
		$div = $('#ProductFinderHelpMePick');
		if ($div.length == 0)
			return;
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: 665,
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');
		var $modalTabs = ModalTabs.setup($div);
		if ($modalTabs) 
			$modalTabs.tabs('select', ProductFinder.index);
	},
	click: function(event) {
			event.preventDefault();
			$div = $('#ProductFinderHelpMePick');
			if ($div.length == 0) {
				$div = $('<div id="ProductFinderHelpMePick" style="display: none;"></div>').appendTo('body');
				$div.load(this.href + ' div.modalContent', ProductFinder.showDialog);
			} else {
				ProductFinder.showDialog();
			}
	}
};

var ModalTabs = {
	setup: function($$) {
		if ($.fn.tabs) {
			return $('div.tabs', $$).tabs( {
				cache: true,
				cleanResponse: function(event, ui) {
					// Strip scripts to prevent problems
					ui.response = ui.response.replace(/<script(.|\s)*?\/script>/g, "");

					var url = $.data(ui.tab, 'href.tabs');
					var contentId = url.substr(url.indexOf('#') + 1);
					if (contentId)
						ui.response = $("<div/>").append(ui.response).find('#' + contentId);
				},
				load: function(event, ui) { },
				select: function(event, ui) {
					// Analytics hook for tab select
					var url = $.data(ui.tab, 'load.tabs');
				},
				show: function(event, ui) {
					if (DD_belatedPNG) {
						$(ui.panel).find('div.shadowBox > div').find(' > div,ul.helpPick li a').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
			});
		}
		return null;
	}
};

var HelpMePick = {
	index: 1,
	hash: 'TabContentHelpMePick',
	init: function() {
		$('a.helpMePick').click(HelpMePick.click);
		$('a.pickResults,a.backToHelpPick').live('click', function(event) {
			event.preventDefault();
			$('#' + HelpMePick.hash + ' .channel .content')
				.load(this.href + ' div.tabContent', function() {
					if (!DD_belatedPNG)
						return;
					$(this)	.find('ul.helpPick li a')
									.each(function(i) {
										DD_belatedPNG.fixPng(this);
					
									});
				});
		});
	},
	showDialog: function() {
		$div = $('#ProductFinderHelpMePick');
		if ($div.length == 0)
			return;
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: 665,
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');		
		var $modalTabs = ModalTabs.setup($div);
		if ($modalTabs)
			$modalTabs.tabs('select', HelpMePick.index);
	},
	click: function(event) {
		event.preventDefault();
		$div = $('#ProductFinderHelpMePick');
		if ($div.length == 0) {
				$div = $('<div id="ProductFinderHelpMePick" style="display: none;"></div>').appendTo('body');
		}
		$div.load(this.href + ' div.modalContent', HelpMePick.showDialog);
	}
};

var LocaleSelector = {
	init: function() {
		$('a#LocaleSelector').click(LocaleSelector.click);
	},
	showDialog: function() {
		$div = $('#LocaleSelectorModalContent');
		if ($div.length == 0)
			return;
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: 665,
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');		
	},
	click: function(event) {
		event.preventDefault();
		$div = $('#LocaleSelectorModalContent');
		if ($div.length == 0) {
			$('body').append('<div id="LocaleSelectorModalContent" style="display: none;"></div>');
		}
		
		//if ($div.length == 0) {
		$('#LocaleSelectorModalContent').load(this.href + ' div.modalContent', LocaleSelector.showDialog);
		//} else {
		//	LocaleSelector.showDialog();
		//}
	}
};

/* 
 * In order to have a table with a fixed column and scrollable "body" we need
 * to do some fancy JS. We setup two divs that will contain the parts (one for
 * the fixed column and one for the body) and put a copy of the necessary table
 * data in each one. Then we use the divs as viewports to control what is visible
 * and how the user can interact with it.
 */
var CompareProducts = {
	columnWidth: 188,
	tableWidth: null,
	init: function() {
		$('a.compare').click(CompareProducts.click);
		this.setup();
	},
	showDialog: function() {
		$div = $('#CompareProductsModalContent');
		if ($div.length == 0)
			return;
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: 891,
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');		
	},
	click: function(event) {
		event.preventDefault();
		$div = $('#CompareProductsModalContent');
		if ($div.length == 0) {
			$('body').append('<div id="CompareProductsModalContent" style="display: none;"></div>');
		}
		$('#CompareProductsModalContent').load(this.href + ' div.modalContent', function() {
			CompareProducts.showDialog();
			CompareProducts.setup();
		});
	},
	setup: function() {
		var $table = $('table.compareProducts');
		if ($table.length == 0)
			return;
		
		// Set table to full width for columns so that we can get the right row height
		this.tableWidth = ($table.find('tr:first td').length * this.columnWidth);
		$table.css('width', this.tableWidth + 'px')
					.find('td').css( { width: this.columnWidth + 'px' } );
					
		$table.find('tr').each( function(i) {
			$(this).find('td:last').addClass('last');
		});
		var $a = $('<a href="#" class="remove">' + localeStrings['remove'] + '</a>');
		$('a.remove').live('click', CompareProducts.removeColumn);
								
		$table.find('tr:first td')
					.prepend($a)
					.end();

		$table.find('tr').each(function(i) {
			var $$ = $(this);
			$$.css( 'height', $$.height() + 'px')
				// explicitly set th and td heights to fix display probs in Safari
				.find('th,td').css( 'height', ($$.height() - 18) + 'px');
		});
		var $tableWrapper = $table.parent();
		var table_html = $tableWrapper.html();

		var groupingBox = '<div class="groupingBox"><div class="header"><div class="content"></div></div><div class="channel"><div class="content selfClear"></div></div><div class="footer"><div class="content"></div></div></div>';

		$tableWrapper.prepend('<div class="columnFixed">' + groupingBox + '</div><div class="tableData"></div>');
	 	$tableWrapper.find('.columnFixed .channel .content') // Find the div that has the fixed column
								.html(table_html)      // populate it with the table data
								.find('td')            // get the tds...
								.remove()              // ...so we can remove them
								.end()                 // reset collection to the div
								.find('table')         // find the table...
								.css('width', '100%');  // ...and make its width match the div

		$tableWrapper.find('.tableData')   // Find the div that has the table data
								.html(table_html)			 // populate it with the table data
								.find('th')						 // Find the th's...
								.remove();             // ...so we can remove them
		$table.remove();
		
		// JS fix for IE6 expanding table when there are more than 5 columns of data
		if (	 $.browser.msie 
				&& ($.browser.version.substr(0,1) == 6)
		) {
			var height = $tableWrapper.find('.tableData table').height();
			$tableWrapper.find('.columnFixed .channel .content').css('height', height + 'px');
		}
		
		// JS fix for IE7 hiding horizontal scroll if less than 4 items.
		if (	 $.browser.msie 
				&& ($.browser.version.substr(0,1) == 7)
		) {
			if($table.find('tr:first td').length < 4){
				$('.modalContent .tableData').css('overflow-x','hidden');			
				}
		}
		
	},
	removeColumn: function(event) {
		event.preventDefault();
		var C = CompareProducts;
		var $td = $(this).parent();
		var index = 0;
		C.tableWidth = C.tableWidth - C.columnWidth;
		$td.parent().children('td').each( function(i) {
			if ($(this).html() == $td.html()) {				
				index = i;
				return; // break
			}
		}).parents('table').find('tr').each( function(i) {
			$(this).children(':eq(' + index + ')').remove();
		}).end().css( 'width', C.tableWidth + 'px' );
		
	}
};

/* Login Box */
var LoginBox = {
  loginLink: null,
  loginBox: null,
  closeLink: null,
  passwordCleared: false,
  usernamePrompt: 'Username',
  usernameField: null,
  passwordField: null,
  init: function() {
    var LB = this;
    LB.loginLink = $('ul.tool a.login');
    LB.loginBox = $('#Login');
    LB.usernameField = LB.loginBox.find('input:eq(0)');
    LB.usernamePrompt = LB.usernameField.val();
    LB.passwordField = LB.loginBox.find('input:eq(1)');
		LB.loginBox.find('a.button').click(function(event) {
			event.preventDefault();
			$(this).parents('form:first').submit();
		});
    LB.closeLink = LB.loginBox.find('a.close').click( LB.close );
    LB.loginLink.click( LB.open ); //.click(); // testing
    LB.usernameField.focus(
      function(e) {
        var $$ = $(this);
        if ($$.val() == LB.usernamePrompt)
          $$.val("");
      }
    ).blur(
      function(e) {
        var $$ = $(this);
        if ($$.val() == "")
          $$.val(LB.usernamePrompt);
      }
    );
    LB.passwordField.focus(
      function(e) {
        if (! LB.passwordCleared)
        {
          LB.passwordField.val("");
          LB.passwordCleared = true;
        }
      }
    );
  },
  close: function(e) {
    e.preventDefault();
    var LB = LoginBox;
    // LB.loginBox.slideUp();
    LB.loginBox.hide();
    LB.loginLink.parent().removeClass('active');
  },
  open: function(e) {
    e.preventDefault();
    var LB = LoginBox;
    // Act like a toggle
    if (LB.loginBox.is(':visible'))
      return LB.close(e);

    // LB.loginBox.slideDown();
		LB.loginBox.show();
    LB.loginLink.parent().addClass('active');
  }
};

// Stub function for possible future usage
function unique(arr) {
	return arr;
}

// Convert an array to an object so we can populate a select list
function arrToObj(arr) {
	var ret = {};
	arr.sort(
		function(a,b){
			if(a==b){
				return 0;
			}
			var b1;
			var b2;
			var a1;
			var a2;
			var aArr=a.split(" ");
			var bArr=b.split(" ");
			if(aArr!=null&&aArr.length>1){
				a1=aArr[0];
				a2=aArr[1];
				
				if(a2=="TB"){
					if(isFloat(a1)){
						a1=a1*1000;
					}else{
						return 0;
					}
					
				}
			}else{
				return -1;
			}
			if(bArr!=null&&bArr.length>1){
				b1=bArr[0];
				b2=bArr[1];
				if(b2=="TB"){
					if(isFloat(b1)){
						b1=b1*1000;
					}else{
						return 0;
					}
				}
				
			}else{
			 	return -1;
			}
			if(isNaN(b1) == true || isNaN(a1) == true ){
				return 0;
			}else{
				return b1-a1;
			}
		}
	);
	for (var i = 0, length = arr.length; i < length; i++) {
		ret[arr[i]] = arr[i];
	}	
	return ret;
}

var ImageViewer = {
	init: function() {
		$('a.gallery').click(ImageViewer.galleryClick);
		this.setup();
	},
	setup: function() {
		if ($.fn.pngFix) {
			$('.heroContainer').pngFix();
		}
		$('ul.thumbnailGrid li').hover(this.thumbnailIn, this.thumbnailOut)
				.find('a').click(this.thumbnailClick);
		$('.imageSpace ul.controls li.previous a').click(this.previousClick);
		$('.imageSpace ul.controls li.next a').click(this.nextClick);
	},
	galleryClick: function(event) {
		event.preventDefault();
		$div = $('#ImageViewerModalContent');
		if ($div.length == 0) {
			$('body').append('<div id="ImageViewerModalContent" style="display: none;"></div>');
		}
		$('#ImageViewerModalContent').load(this.href + ' div.modalContent', function() {
			ImageViewer.showDialog();
			ImageViewer.setup();
		});
	},
	showDialog: function() {
		$div = $('#ImageViewerModalContent');
		if ($div.length == 0)
			return;
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: 751,
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');		
	},
	thumbnailIn: function(event) {
		var $$ = $(this).addClass('over');
		if ($$.hasClass('active')) return;
		ImageViewer.activateThumbnailImage($$);
	},
	thumbnailOut: function(event) {
		var $$ = $(this).removeClass('over');
		if ($$.hasClass('active')) return;
		ImageViewer.deactivateThumbnailImage($$);
	},
	thumbnailClick: function(event) {
		event.preventDefault();
		var $$ = $(this);
		$('.heroContainer > img').attr('src', $$.attr('href'));
		if ($.fn.pngFix) {
			// Re-run png fix whenever we switch images because the image changes.
			$('.heroContainer').pngFix();
		}
		var $li = $$	.parent() // li
									.siblings('.active') // active li's
									.each(function(i) { // make inactive and fix image
										ImageViewer.deactivateThumbnailImage($(this).removeClass('active'));
									})
									.end() // back to "this" li
									.addClass('active'); // Make it active
		ImageViewer.activateThumbnailImage($li);
		$('.imageSpace ul.controls li.title').text($$.attr('title'));
	},
	activateThumbnailImage: function($li) {
		var $img = $li.find('img');
		var src = $img.attr('src');
		src = src.replace(/grey-bg/,'white-bg');
		$img.attr('src', src);
	},
	deactivateThumbnailImage: function($li) {
		var $img = $li.find('img');
		var src = $img.attr('src');
		src = src.replace(/white-bg/,'grey-bg');
		$img.attr('src', src);
	},
	previousClick: function(event) {
		event.preventDefault();
		var $prev = $('ul.thumbnailGrid li.active').prev();
		if ($prev.length == 0)
			$prev = $('ul.thumbnailGrid li.active').siblings(':last');
			
		$prev.find('a').click();
	},
	nextClick: function(event) {
		event.preventDefault();
		var $next = $('ul.thumbnailGrid li.active').next();
		if ($next.length == 0)
			$next = $('ul.thumbnailGrid li.active').siblings(':first');
			
		$next.find('a').click();
	}
};

var FlashVideo = {
	currColor: '',
	selectedIndex: 0,
	flashVideo: [],
	flashData: null,
	init: function() {
		var FV = FlashVideo;
		FV.flashVideo = $('a.flashVideo').click(FlashVideo.click);
		
		if (FV.flashVideo.length == 0) return;

	},
	showDialog: function() {
		var $div = $('#FlashPlayerModal');
		if ($div.length == 0)
			return;
		var flashData = FlashVideo.flashData;
		if (! flashData)
			return;
			
		swfobject.embedSWF(flashData['swf'], 'ModalFlashContainer', flashData['width'], flashData['height'], flashData['version'], flashData['express'], flashData['flashVars'], flashData['params'], flashData['attributes']);
		
		$dialog = $div.dialog({
				draggable: false,
				modal: true,
				bgiframe: true,
				width: parseInt(flashData['width']) + 32,
				// height: flashData['height'],
				closeText: localeStrings['close'],
				resizable: false,
		   	open: function(event, ui) {
					if (DD_belatedPNG) {
						// Fix each DOM element because applying the fix to a CSS selector
						// doesn't work when we dynamically load content via AJAX
						ui.dialog.find('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
							DD_belatedPNG.fixPng(this);
						});
					}
				}
		}).dialog('open');		
	},
	setupFlashPlayer: function(flashModal) {
		$div = $('#FlashPlayerModal');
		if ($div.length == 0) {
			$div = $('<div id="FlashPlayerModal" style="display: none;"></div>').appendTo('body');
			$div.load(flashModal + ' div.modalContent', FlashVideo.showDialog);
		} else {
			FlashVideo.showDialog();
		}
	},
	click: function(event) {
		if ($(this).hasClass('flashVideo')) {
			event.preventDefault();

		var vurl = $(this).attr('href');
		var pid = $(this).getUrlParam("pid");
		var plist = $(this).getUrlParam("plist");
		var vid = $(this).getUrlParam("vid");
		var w = $(this).getUrlParam("w");
		var h = $(this).getUrlParam("h");

		var flashData = {
			flashVars: {
				videoid: vid,
				playerid: pid,
				playlist: plist,
				vwidth: w,
				vheight: h
				},
			params: { wmode: 'transparent', scale:'noScale', salign:'tl', menu:'false', allowScriptAccess:'always' },
			attributes: { id:'ModalFlashContainer', name:'ModalFlashContainer' },
			swf: '/images/flash/video/brightcove-wrapper.swf',
			width: w,
			height: h,
			version: '9.0.115',
			express: '/images/flash/video/expressInstall.swf'
		} 
			FlashVideo.flashData = flashData;
			FlashVideo.setupFlashPlayer(vurl);
		} else {
			FlashVideo.select(this);
		}
	}
};

var IEMarginFix = {
	previousSiblingMargin: function(elm) {
		var margin = $(elm).prev().css('margin-bottom');
		var result = margin.match(/\d+/g);
		return result[0];
	},
	fixMargin: function(elm) {
		var margin = IEMarginFix.previousSiblingMargin(elm);
		if (margin > 0) {
			return '0';
		}
		return '15px';
	}
};

/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 */
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/ 
 getURLParam: function(strParamName){
	  var strReturn = "";
	  var strHref = window.location.href;
	  var bFound=false;
	  
	  var cmpstring = strParamName + "=";
	  var cmplen = cmpstring.length;

	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        bFound=true;
	        break;
	      }
	      
	    }
	  }
	  if (bFound==false) return null;
	  return strReturn;
	}
});

$(document).ready( function() {
	/* Make display: inline-block work correctly in Firefox 2 */
	if ( $.browser.mozilla && $.browser.version.substr(0,3) == '1.8') {
		$('ul#NavigationPrimary ul.sections > li, ul.grid > li').wrapInner('<div></div>');
		$('body').addClass('fx2');
	} else if ( $.browser.opera ) {
		$('body').addClass('opera');
	}


	ProductInfoSelector.init();
	SectionInfoBlock.init();
	
	$('#NavigationPrimary > li').hover( 
		function(e) {
			$(this).addClass('over');
			if ($.fn.bgiframe)
				$(this).children('div:first').bgiframe();
		}, 
		function(e) { 
			$(this).removeClass('over');
		}
	);
	ProductInfoSelector.setupPricingInfo();
	ProductInfoSelector.setupPopInfo();
	if ($.fn.tabs) {
		$tabs = $('div.tabs,div.tabHeader').tabs( {
			show: function(event, ui) {
				if ($.fn.pngFix) {
					// Re-run png fix whenever we switch tabs because the background image changes.
					$('ul.tabNav').pngFix();
				}
			},
			// set url hash to selected tab 
            select: function(event, ui){
                 document.location.hash = "t" + $(ui.panel).attr("id");
            }
		});
		// go to tab set in url 
        $tabs.tabs('select', document.location.hash.slice(2));
	}
	 	ProductShots.init();
	// ColorPicker is inited by ProductInfoSelector
	// ColorPicker.init();
	Toolbar.init();
	
	if ($.fn.newsticker)
		$('#News ul').newsticker();
	
	if ($.fn.jcarousel) {
		function mycarousel_initCallback(carousel) {
				$(carousel.container).find('.jcarousel-next').bind('click', function(event) {
					event.preventDefault();
					carousel.next();
					return false;
				});
	
				$(carousel.container).find('.jcarousel-prev').bind('click', function(event) {
					event.preventDefault();
					carousel.prev();
					return false;
				});
		};
		function mycarousel_itemVisibleInCallback(carousel) { };

		// Only activate the carousel if we have more than one promo
		$('div.promoCarousel').each(function(i) {
			if ($(this).find(' > ul.promoList > li').length > 1) {
				$(this).jcarousel(
					{
						scroll: 1,
						wrap: 'both',
						initCallback: mycarousel_initCallback,
						itemVisibleInCallback: mycarousel_itemVisibleInCallback,
						// This tells jCarousel NOT to autobuild prev/next buttons
						buttonNextHTML: '<a href="#" class="jcarousel-next carouselControl">' + localeStrings.next + '</a>',
						buttonPrevHTML: '<a href="#" class="jcarousel-prev carouselControl">' + localeStrings.previous + '</a>'
					}
				);
			} // if
		});
	} // if ($.fn.jcarousel)
	
	$('.ui-widget-overlay').live('click', function(event) {
		if ($dialog) {
			$dialog.dialog('close');
		}
	});
	$('div.purchaseContainer.focusBox')
		.find("input[name=quantity]:not('.changeEvent')")
		.keyup(function(event) {
			var $a = $(this).next('a');
			if ($a.length == 0) return;
			var href = $a.attr('href');
			if (href.search(/quantity\.\d+/) == -1) {
				$a.attr('href', href + '/quantity.' + $(this).val());
			} else {
				$a.attr('href', href.replace(/quantity\.\d+/, 'quantity.' + $(this).val()));
			}
		});

	ProductFinder.init();

	LoginBox.init();

	HelpMePick.init();

	LocaleSelector.init();

	CompareProducts.init();

	CartInfo.init();
	
	if (DD_belatedPNG) {
		// Fix each DOM element because applying the fix to a CSS selector
		// doesn't work when we dynamically load content via AJAX
		$('div.shadowBox > div').find(' > div').andSelf().each( function(i) {
			DD_belatedPNG.fixPng(this);
		});
	}
		
	ImageViewer.init();
	FlashVideo.init();
	// JS fix for IE not supporting abutting margins to collapse to largest
	if (	 $.browser.msie 
			&& ($.browser.version.substr(0,1) == 6 || $.browser.version.substr(0,1) == 7)
	) {
		// Stylesheet to contain our dynamic expression for margin collapse behavior.
		var style = document.createElement('style');
		document.documentElement.firstChild.insertBefore(style, document.documentElement.firstChild.firstChild);
		var styleSheet = style.styleSheet;
		styleSheet.addRule('hr', 'margin-top:expression(IEMarginFix.fixMargin(this))');
	}
  an_postPrintHandler = function() {
  	// "Unmark" the tabs as tabs so that the tabs JS doesn't hide the content.
  	$('ul.tabNav, .tabHeader').hide();
		$('.ui-tabs-hide').removeClass('ui-tabs-hide');

		// tab navigation not in a tabHeader should be inserted before it's content
		$('ul.tabNav').each(function(i) {
			if ($(this).parents('.tabHeader').length > 0)
				return;
			$(this).find('a').each(function(j) {
				$(this.hash).prepend('<h2>' + $(this).text() + '</h2>');
			});
		});
		if (window.print && jQuery.getURLParam("print")==1) {
      setTimeout("window.print()", 500); // dialog on demand - delayed so that page loads before dialog appears
		}
  };
	if ($.fn.popupwindow)
  	$('a.print').popupwindow(); 
	if ($.fn.printPage) {
	  $('#ContentChannel a').not($('ul.tabs a'))
		                    .not($('.ecommerce a.addToCart'))
		                    .not($('#Breadcrumbs a'))
		                    .not($('ul.expandableContent > li > a.title'))
		                    .not($('div.linksWithDates a.more'))
		                    .not($('div.linksWithDates a.prev'))
		                    .not($('div.searchBox a'))
		                    .not($('div.ecommerce a'))
		                    .not($('div.paginated a'))
		                    .printPage({ // Footnote the content
													postPrintHandler: an_postPrintHandler,
													footnoteLinks: false
	                      });
	}
});


//extracts the 5 character local ("en-us" etc.) from a www url and returns it in lowercase.
function getLocale(){
	var url = window.location.toString();
	var locale_re1 = /.*\/www\/(..-..)\/.*/;
	var locale_re2 = /.*locale=(..-..).*/;
	var locale_re3 = /.*localePath=(..-..).*/;
	var locale = url.replace(locale_re1, "$1");
	locale = locale.replace(locale_re2, "$1");
	if(locale.length != 5){
		locale = locale.replace(locale_re3, "$1");
	}
	if(locale.length != 5){
		locale="en-us"; //default to en-us if string was not matched
	}
	locale = locale.toLowerCase();
	return locale;
}

function setOpenAccordion(my_locales){
	var expanded_re = /..-..=(\d)/;	
	var expanded;
	var this_locale = getLocale();
	for (i=0; i<my_locales.length; i++){
		if(my_locales[i].indexOf(this_locale)!=-1){
			expanded=my_locales[i].replace(expanded_re, "$1");
		}	
	}	
	expanded--;
	return expanded;
}

function isFloat(s){   
	   var path=/^(-?\d+)(\.\d+)?$/;   
	   if (path.test(s)){
			return   true;
	   }else{ 
			return   false;
		}
  }  
