// prevent firebug console log errors
(function(){
	if (!window.console || !console.firebug) {
		var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
		
		window.console = {};
		for (var i = 0; i < names.length; i++) {
			window.console[names[i]] = function(){};
		}
	}
})();

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;
		//Commented this if statement for QC 1619 by Hua Shuai at 2010-8-5
		//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');		
	}
};

// 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');
	DD_belatedPNG.fix('.promoTile .header,.promoTile .header .content,.promoTile .footer,.promoTile .footer .content');
}

// Handle user picking colors.
var ColorPicker = {
	selectedColor: '',
	pickers: [],
	colorLookup: { },
	init: function(colors) {
		//console.log("C.init");
		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,model) {
		//console.log("C.updateColors");
		//todo: don't do anything if color block doesn't exist
		var C = ColorPicker;
		var P = ProductInfoSelector;
		//var model = P.currentModel();
		var currentColor = model.color;
				
		C.pickers.find('ul li').removeClass();
		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) {
				// the color is in the array
				if (color == currentColor && P.overField == null) {
					$li.addClass('selected');
					$('#ProductColor').text($li.find('img').attr('alt'));
				} else if (color == currentColor && P.overField == 'color') {
					$li.addClass('over');
				}
			} else if ($li.is(':visible')) {
				// the color is not in the array
				$li.addClass('selectedUnavailable');
				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) {
		//console.group("C.over");
		if($(this).hasClass('selectedUnavailable')) {
			$(this).addClass('overUnavailable');
		} else {
			$(this).addClass('over');
		}
		var P = ProductInfoSelector;
		P.overField = 'color'; // field that was mouse over
		P.saveCurrentModel = P.model; // save the current model choice
		var $img =
			$(this)	.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
		P.color = ColorPicker.retrieveColor($img);
		P.resetModelListOver();
		P.updateFields();
		//console.groupEnd();
	},
	out: function(event) {
		//console.group("C.out");
		if($(this).hasClass('overUnavailable')) {
			$(this).removeClass('overUnavailable');
		} else {
			$(this).removeClass('over');
		}
		var P = ProductInfoSelector;
		P.restoreSelections();
		P.resetModelList();
		P.updateFields();
		//console.groupEnd();
	},
	click: function(event) {
		event.preventDefault();
		ColorPicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		//console.group("C.handleClick");
		var P = ProductInfoSelector
		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);
		//console.log("selectedColor:"+ColorPicker.selectedColor);
		//P.colorChanged( ColorPicker.selectedColor, $(li).find('img').attr('alt'), dont_track_selector_update );
		P.overField = null;
		P.changeField = 'color';
		P.color = P.selectionHistory.color = ColorPicker.selectedColor;
		P.selectionAttributeHistory.push('color');
		//console.log(P.color);
		P.resetModelList();
		P.updateFields();
		try{P.updateSKU();}catch(e){}
		ProductShots.showModel( P.model );
		//console.groupEnd();
	},
	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;
	}
	
};

var CapacityPicker = {
	selectedCapacity: '',
	pickers: [],
	init: function(modelList) {
		//console.log("CP.init");
		var CP = CapacityPicker;
		var $pickers = CP.pickers = $('#capacityPicker');
		if ($pickers.length == 0) {
			CP.selectedCapacity = 'no_capacity';
			return false;
		}
		
		var P = ProductInfoSelector;
		//console.log(arrToObj(P.capacityList(modelList)));
		var index_lx=0;
		if($('#capacityPicker').length!=0) {
			$.each(
			 arrToObjForCapacityOrderByType(P.capacityList(modelList),product_type),
			 function(i,objValue) {
				 //liuxiao
				 if(objValue!=null && objValue!="" && objValue!="null")
				 {
					CP.pickers.children('ul').append('<li><span>'+objValue+'</span></li>'); // add each capacity
					if(index_lx==0)
					{
						P.maxcapacity=objValue;
						index_lx=index_lx+1;
					}
				 }
				 
			 }
			);
		} else {
			return;	
		}
		CP.pickers.children('ul').children('li').hover(CP.over, CP.out).click(CP.click);
	},
	updateCapacity: function(modelList,model) {
		//console.log("CP.updateCapacity");
		if($('#capacityPicker').length != 0) {
			var P = ProductInfoSelector;
			var CP = CapacityPicker;
			var arr = P.capacityList(modelList);
			//console.dir(arr);
			//var model = P.currentModel();
			var currentCapacity = model.capacity;
			
			// clear the classes for all items and reset them for current product
			$('#capacityPicker').find('li').removeClass().each(function(i) {
				if($.inArray($(this).children('span').text(),arr) == -1) {
					$(this).addClass('selectedUnavailable'); // mark as unavailable if the capacity is not in list
				} else {
					//if($(this).hasClass('selectedUnavailable')) $(this).removeClass('selectedUnavailable'); // make sure any previously unavailable capacities are set to available
					if($(this).text() == currentCapacity && P.overField == null) {
						$(this).addClass('selected'); // mark currently selected product capacity as selected
						$('#ProductCapacity').text(currentCapacity);
					} else if($(this).text() == currentCapacity && P.overField == "capacity") {
						$(this).addClass('over');
					}
				}
			});
		} else {
			return;	
		}
	},
	over: function(event) {
		//console.group("CP.over()");
		if($(this).hasClass('selectedUnavailable')) {
			$(this).addClass('overUnavailable');
		} else {
			$(this).addClass('over');
		}
		var P = ProductInfoSelector;
		P.overField = 'capacity'; // field that was mouse over
		P.saveCurrentModel = P.model; // save the current model choice
		P.capacity = $(this).children('span').text();
		P.resetModelListOver();
		P.updateFields();
		//console.groupEnd();
	},
	out: function(event) {
		//console.group("CP.out()");
		if($(this).hasClass('overUnavailable')) {
			$(this).removeClass('overUnavailable');
		} else {
			$(this).removeClass('over');
		}
		var P = ProductInfoSelector;
		P.restoreSelections();
		P.resetModelList();
		P.updateFields();
		//console.groupEnd();
	},
	click: function(event) {
		event.preventDefault();
		CapacityPicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		//console.group("CP.handleClick()");
		var P = ProductInfoSelector;
		$(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
		P.overField = null; // make sure to forget overfield
		P.changeField = 'capacity';
		P.capacity = P.selectionHistory.capacity = CapacityPicker.selectedCapacity = $(li).children('span').text();
		P.selectionAttributeHistory.push('capacity');
		//console.log(P.capacity);
		P.resetModelList();
		P.updateFields();
		try{P.updateSKU();}catch(e){}
		ProductShots.showModel( P.model );
		//console.groupEnd();
	}
};

var InterfacePicker = {
	selectedInterface: '',
	pickers: [],
	init: function(modelList) {
		//console.log("IP.init");
		var IP = InterfacePicker;
		var $pickers = IP.pickers = $('#interfacePicker');
		if ($pickers.length == 0) {
			IP.selectedInterface = 'no_interface';
			return false;
		}
		
		var P = ProductInfoSelector;
		if($('#interfacePicker').length!=0) {
			
			$.each(
			 arrToObjForCapacity(P.interfaceList(modelList).sort()),
			 function(i,objValue) {
			 //liuxiao
				if(objValue!=null && objValue!="" && objValue!="null")
				{
					IP.pickers.children('ul').append('<li><span>'+objValue+'</span></li>'); // add each interface
				}
			 }
			);
			
		} else {
			return;	
		}
		IP.pickers.children('ul').children('li').hover(IP.over, IP.out).click(IP.click);

	},
	updateInterface: function(modelList, model) {
		//console.log("IP.updateInterface");			
		if($('#interfacePicker').length != 0) {
			
			var P = ProductInfoSelector;
			var IP = InterfacePicker;
			var arr = P.interfaceList(modelList);
			//console.dir(arr);
			//var model = P.currentModel();
			var currentInterface = model.interface;
			
			// clear the classes for all items and reset them for current product
			$('#interfacePicker').find('li').removeClass().each(function(i) {
				if($.inArray($(this).children('span').text(),arr) == -1) {
					$(this).addClass('selectedUnavailable'); // mark as unavailable if the interface is not in list
				} else {
					//if($(this).hasClass('selectedUnavailable')) $(this).removeClass('selectedUnavailable'); // make sure any previously unavailable interfaces are set to available
					if($(this).text() == currentInterface && P.overField == null) {
						$(this).addClass('selected'); // mark currently selected product interface as selected
						$('#ProductInterface').text(currentInterface);
					} else if ($(this).text() == currentInterface && P.overField == "interface") {
						$(this).addClass('over');
					}
				}
			});
		} else {
			return;	
		}
	},
	over: function(event) {
		//console.group("IP.over")
		if($(this).hasClass('selectedUnavailable')) {
			$(this).addClass('overUnavailable');
		} else {
			$(this).addClass('over');
		}
		var P = ProductInfoSelector;
		P.overField = 'interface'; // field that was mouse over
		P.saveCurrentModel = P.model; // save the current model choice
		P.interface = $(this).children('span').text();
		P.resetModelListOver();
		P.updateFields();
		//console.groupEnd();
	},
	out: function(event) {
		//console.group("IP.out")
		if($(this).hasClass('overUnavailable')) {
			$(this).removeClass('overUnavailable');
		} else {
			$(this).removeClass('over');
		}
		var P = ProductInfoSelector;
		P.restoreSelections();
		P.resetModelList();
		P.updateFields();
		//console.groupEnd();
	},
	click: function(event) {
		event.preventDefault();
		InterfacePicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		//console.group("IP.handleClick")
		var P = ProductInfoSelector;
		$(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
		P.overField = null; // make sure to forget overfield
		P.changeField = 'interface';
		P.interface = P.selectionHistory.interface = InterfacePicker.selectedInterface = $(li).children('span').text();
		P.selectionAttributeHistory.push('interface');
		//console.log(P.interface);
		P.resetModelList();
		P.updateFields();
		try{P.updateSKU();}catch(e){}
		ProductShots.showModel( P.model );
		//console.groupEnd();
	}
};

var OptionsPicker = {
	selectedOption: '',
	pickers: [],
	init: function(modelList) {
		//console.log("OP.init");
		var OP = OptionsPicker;
		var $pickers = OP.pickers = $('#optionsPicker');
		if ($pickers.length == 0) {
			OP.selectedOption = 'no_options';
			return false;
		}
		
		var P = ProductInfoSelector;
		if($('#optionsPicker').length!=0) {
			
			$.each(
			 //arrayUnique(P.optionsList(modelList)).sort(),
			 arraySortUniqueForOptions(P.optionsList(modelList),P.optionsList_en(modelList)),
			 function(i,objValue) {
				//liuxiao added
				if(objValue!=null && objValue!="" && objValue!="null")
				{
				 OP.pickers.children('ul').append('<li><span>'+objValue+'</span></li>'); // add each interface
				}
			 }
			);
			OP.pickers.children('ul').children('li').hover(OP.over, OP.out).click(OP.click);
			P.buildToolTip(modelList);
			
		} else {
			return;	
		}

	},
	updateOptions: function(modelList,model) {
		//console.log("OP.updateOptions");		
		if($('#optionsPicker').length != 0) {
			var P = ProductInfoSelector;
			var OP = OptionsPicker;
			var arr = P.optionsList(modelList);
			//console.dir(arr);
			//var model = P.currentModel();
			var currentOption = null;
			if (model.options[0]) {
				currentOption = model.options[0].name;// options is an array
			}
			//liuxiao
			if((currentOption == null || currentOption=="") && P.overField == null) $('#ProductOptions').hide(); // some models within a set have no options so we hide it
						
			//console.log("currentOption:"+currentOption);
			// clear the classes for all items and reset them for current product
			$('#optionsPicker').find('li').removeClass().each(function(i) {
				// Added by Hua Shuai at 2010-7-22 for QC 1539. Convert the value of span element by using replaceSpecialCharacter() method
				var spanText=replaceSpecialCharacter($(this).children('span').text());
				if($.inArray(spanText,arr) == -1) {
					$(this).addClass('selectedUnavailable'); // mark as unavailable if the option is not in list
				} else {
					//if($(this).hasClass('selectedUnavailable')) $(this).removeClass('selectedUnavailable'); // make sure any previously unavailable option are set to available
					//console.log("this.text:"+$(this).text());
					if(spanText == currentOption && P.overField == null) {
						//$(this).text(),currentOption) > -1 && P.overField == null
						$(this).addClass('selected'); // mark currently selected product option as selected
						$('#ProductOptions').html(currentOption);
						$('#ProductOptions').show();
					} else if(spanText == currentOption && P.overField == "options") {
						$(this).addClass('over');
					}
				}
			});
		} else {
			return;	
		}
	},
	over: function(event) {
		//console.group("OP.over()");
		if($(this).hasClass('selectedUnavailable')) {
			$(this).addClass('overUnavailable');
		} else {
			$(this).addClass('over');
		}
		var P = ProductInfoSelector;
		P.overField = 'options'; // field that was mouse over
		P.saveCurrentModel = P.model; // save the current model choice
		P.options = $(this).children('span').text();
		P.resetModelListOver();
		P.updateFields();
		//console.groupEnd();
	},
	out: function(event) {
		//console.group("OP.out()");
		if($(this).hasClass('overUnavailable')) {
			$(this).removeClass('overUnavailable');
		} else {
			$(this).removeClass('over');
		}
		var P = ProductInfoSelector;
		P.restoreSelections();
		P.resetModelList();
		P.updateFields();
		//console.groupEnd();
	},
	click: function(event) {
		event.preventDefault();
		OptionsPicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		//console.group("OP.handleClick()");
		var P = ProductInfoSelector;
		$(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
		P.overField = null; // make sure to forget overfield
		P.changeField = 'options';
		P.options = P.selectionHistory.options = OptionsPicker.selectedOption = $(li).children('span').text();
		P.selectionAttributeHistory.push('options');
		//console.log(P.options);
		P.resetModelList();
		P.updateFields();
		try{P.updateSKU();}catch(e){}
		ProductShots.showModel( P.model );
		//console.groupEnd();
	}
};

var CachePicker = {
	selectedCache: '',
	pickers: [],
	init: function(modelList) {
		//console.log("CHP.init");
		var CHP = CachePicker;
		var $pickers = CHP.pickers = $('#cachePicker');
		if ($pickers.length == 0) {
			CHP.selectedCache = 'no_cache';
			return false;
		}
		
		var P = ProductInfoSelector;
		var index_lx=0;
		if($('#cachePicker').length!=0) {
			
			$.each(
			arrToObjForCacheOrder(P.cacheList(modelList)),
			 //arrToObjForCapacity(P.cacheList(modelList)),
			 function(i,objValue) {
				//liuxiao added
				if(objValue!=null && objValue!="" && objValue!="null")
				{
					CHP.pickers.children('ul').append('<li><span>'+objValue+'</span></li>'); // add each cache
					if(index_lx==0)
					{
						P.maxcache=objValue;
						index_lx=index_lx+1;
					}
				}
				
			 }
			);
			
		} else {
			return;	
		}
		CHP.pickers.children('ul').children('li').hover(CHP.over, CHP.out).click(CHP.click);

	},
	updateCache: function(modelList,model) {
		//console.log("CHP.updateCache");
		if($('#cachePicker').length != 0) {
			var P = ProductInfoSelector;
			var CHP = CachePicker;
			var arr = P.cacheList(modelList);
			//console.dir(arr);
			//var model = P.currentModel();
			var currentCache = model.cache;
			
			// clear the classes for all items and reset them for current product
			$('#cachePicker').find('li').removeClass().each(function(i) {
				if($.inArray($(this).children('span').text(),arr) == -1) {
					$(this).addClass('selectedUnavailable'); // mark as unavailable if the cache is not in list
				} else {
					//if($(this).hasClass('selectedUnavailable')) $(this).removeClass('selectedUnavailable'); // make sure any previously unavailable cache are set to available
					if($(this).text() == currentCache && P.overField == null) {
						$(this).addClass('selected'); // mark currently selected product cache as selected
						$('#ProductCache').text(currentCache);
					} else if ($(this).text() == currentCache && P.overField == "cache") {
						$(this).addClass('over');
					}
				}
			});
		} else {
			return;	
		}
	},
	over: function(event) {
		//console.group("CHP.over()");
		if($(this).hasClass('selectedUnavailable')) {
			$(this).addClass('overUnavailable');
		} else {
			$(this).addClass('over');
		}
		var P = ProductInfoSelector;
		P.overField = 'cache'; // field that was mouse over
		P.saveCurrentModel = P.model; // save the current model choice
		P.cache = $(this).children('span').text();
		P.resetModelListOver();
		P.updateFields();
		//console.groupEnd();
	},
	out: function(event) {
		//console.group("CHP.out()");
		if($(this).hasClass('overUnavailable')) {
			$(this).removeClass('overUnavailable');
		} else {
			$(this).removeClass('over');
		}
		var P = ProductInfoSelector;
		P.restoreSelections();
		P.resetModelList();
		P.updateFields();
		//console.groupEnd();
	},
	click: function(event) {
		event.preventDefault();
		CachePicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		//console.group("CHP.handleClick()");
		var P = ProductInfoSelector;
		$(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
		P.overField = null; // make sure to forget overfield
		P.changeField = 'cache';
		P.cache = P.selectionHistory.cache = CachePicker.selectedCache = $(li).children('span').text();
		P.selectionAttributeHistory.push('cache');
		//console.log(P.cache);
		P.resetModelList();
		P.updateFields();
		try{P.updateSKU();}catch(e){}
		ProductShots.showModel( P.model );
		//console.groupEnd();
	}
};

var SpinSpeedPicker = {
	selectedSpinSpeed: '',
	pickers: [],
	init: function(modelList) {
		//console.log("SP.init");
		var SP = SpinSpeedPicker;
		var $pickers = SP.pickers = $('#spinSpeedPicker');
		if ($pickers.length == 0) {
			SP.selectedSpinSpeed = 'no_spin_speed';
			return false;
		}
		
		var P = ProductInfoSelector;
		var index_lx=0;
		if($('#spinSpeedPicker').length!=0) {
			
			$.each(
			 //arrToObjForCapacity(P.spinSpeedList(modelList)),
			 //arrToObjForCacheOrder(P.spinSpeedList(modelList)),
			 //QC 1708, add a new function to sort spinspeed
			 sortSpinSpeed(P.spinSpeedList(modelList)),
			 function(i,objValue) {
				//liuxiao
				 if(objValue!=null && objValue!="" && objValue!="null")
				 {
					SP.pickers.children('ul').append('<li><span>'+objValue+'</span></li>'); // add each spin speed
					if(index_lx==0)
					{
						P.maxspinspeed=objValue;
						index_lx=index_lx+1;
					}
					
				 }
			 }
			);
			
		} else {
			return;	
		}
		SP.pickers.children('ul').children('li').hover(SP.over, SP.out).click(SP.click);

	},
	updateSpinSpeed: function(modelList,model) {
		//console.log("SP.updateSpinSpeed");
		if($('#spinSpeedPicker').length != 0) {
			var P = ProductInfoSelector;
			var SP = SpinSpeedPicker;
			var arr = P.spinSpeedList(modelList);
			//console.dir(arr);
			//var model = P.currentModel();
			var currentSpinSpeed = model.spinSpeed;
			
			// clear the classes for all items and reset them for current product
			$('#spinSpeedPicker').find('li').removeClass().each(function(i) {
				if($.inArray($(this).children('span').text(),arr) == -1) {
					$(this).addClass('selectedUnavailable'); // mark as unavailable if the interface is not in list
				} else {
					if($(this).hasClass('selectedUnavailable')) $(this).removeClass('selectedUnavailable'); // make sure any previously unavailable interfaces are set to available
					if($(this).text() == currentSpinSpeed && P.overField == null) {
						$(this).addClass('selected'); // mark currently selected product interface as selected
						$('#ProductSpinSpeed').text(currentSpinSpeed);
					} else if ($(this).text() == currentSpinSpeed && P.overField == "spinSpeed") {
						$(this).addClass('over'); 	
					}
				}
			});
		} else {
			return;	
		}
	},
	over: function(event) {
		//console.group("SP.over()");
		if($(this).hasClass('selectedUnavailable')) {
			$(this).addClass('overUnavailable');
		} else {
			$(this).addClass('over');
		}
		var P = ProductInfoSelector;
		P.overField = 'spinSpeed'; // field that was mouse over
		P.saveCurrentModel = P.model; // save the current model choice
		P.spinSpeed = $(this).children('span').text();
		P.resetModelListOver();
		P.updateFields();
		//console.groupEnd();
	},
	out: function(event) {
		//console.group("SP.out()");
		if($(this).hasClass('overUnavailable')) {
			$(this).removeClass('overUnavailable');
		} else {
			$(this).removeClass('over');
		}
		var P = ProductInfoSelector;
		P.restoreSelections();
		P.resetModelList();
		P.updateFields();
		//console.groupEnd();
	},
	click: function(event) {
		event.preventDefault();
		SpinSpeedPicker.handleClick(this);
	},
	handleClick: function(li, dont_track_selector_update) {
		//console.group("SP.handleClick()");
		var P = ProductInfoSelector;
		$(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
		P.overField = null; // make sure to forget overfield
		P.changeField = 'spinSpeed';
		P.spinSpeed = P.selectionHistory.spinSpeed = SpinSpeedPicker.selectedSpinSpeed = $(li).children('span').text();
		P.selectionAttributeHistory.push('spinSpeed');
		//console.log(P.spinSpeed);
		P.resetModelList();
		P.updateFields();
		try{P.updateSKU();}catch(e){}
		ProductShots.showModel( P.model );
		//console.groupEnd();
	}
};

// Control product info dropdowns and add to cart button
var ProductInfoSelector = {
	color: null,
	capacity: null,
	'interface': null,
	cache: null,
	options: null,
	spinSpeed: null,
	product: null,
	sku: null,
	releaseIndex: 0,
	modelIndex: 0,
	changeField: null,
	saveChangeField: null,
	defaultSubtitle: null,
	subtitleElm: null,
	//currentModel: null,
	saveCurrentModel: null,
	selectionHistory: [],
	selectionAttributeHistory: [],
	//added by liuxiao for QC1485
	maxcache: null,
	maxcapacity: null,
	maxoption: null,
    maxspinspeed: null,
	//selectionHistory: [{color:null,capacity:null,interface:null,cache:null,options:null,spinSpeed:null}],
	
	init: function() {
		//console.group("P.init()");
		if (! ProductInfoStruct)
			return false;
		
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		//P.color = ColorPicker.selectedColor;
		//console.log(P.color);
		//ProductInfoStruct.releaseList[0].modelList[0].options[0]
		
		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));
		CapacityPicker.init(modelList);
		InterfacePicker.init(modelList);
		OptionsPicker.init(modelList);
		CachePicker.init(modelList);
		SpinSpeedPicker.init(modelList);
		
		P.setDefaultAttribute();
		//CapacityPicker.updateCapacity(P.currentModelList());
		P.updatePulldowns();
		
		//Added by Hua Shuai for QC 1619 at 2010-8-5
		ProductShots.showModel(P.model);

		//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));
		//console.groupEnd();
	},
	setDefaultAttribute: function() {
		// On page load we need to determine which attribute to use as the default filter
		//console.log("P.setDefaultAttribute()");
		var P = ProductInfoSelector;
		var model = P.currentModel();
		
		if ($('.colorPicker').length!=0) {
			//console.log("color");
			P.capacity = model.capacity; //make capacity default so color choices display
			P.changeField = 'capacity';
		} else if ($('#capacityPicker').length!=0) {
			//console.log("capacity");
			P.interface = model.interface; //make interface default so capacity choices display
			P.changeField = 'interface';
		} else if ($('#interfacePicker').length!=0) {
			//console.log("interface");
			P.interface = model.interface;
			P.changeField = 'interface';
		} else if ($('#optionsPicker').length!=0) {
			//console.log("options");
			if(model!=null&&model!="undefined"&&model.options[0]!=null&&model.options[0]!="undefined"){
				P.options = model.options[0].name;
				P.changeField = 'options';
			}
			
		} else if ($('#cachePicker').length!=0) {
			//console.log("cache");
			P.cache = model.cache;
			P.changeField = 'cache';
		} else if ($('#spinSpeedPicker').length!=0){
			//console.log("spinspeed");
			P.spinSpeed = model.spinSpeed;
			P.changeField = 'spinSpeed';
		} else {
			//console.log("other");
			P.capacity = model.capacity;
			P.changeField = 'capacity';
		}
		
	},
	checkAvailableAttributes: function() {
		//No longer used 04.01.10
		// Save previous selections if they are still available in the current combination
		var P = ProductInfoSelector;
		//console.log(P.currentModelList());
		if ($.inArray(ColorPicker.selectedColor,P.currentModelList()) == -1) {
			//console.log("selectedcolor not in currentmodellist");
			P.color = null;
		}
	},
	resetModelList: function() {
		// Reset modelList based on what was selected
		var P = ProductInfoSelector;
		if (P.changeField == 'color') {
			P.capacity = P['interface'] = P.options = P.cache = P.spinSpeed = null;
		} else if (P.changeField == 'capacity') {
			P.color = P['interface'] = P.options = P.cache = P.spinSpeed = null;
		} else if (P.changeField == 'interface') {
			P.color = P.capacity = P.options = P.cache = P.spinSpeed = null;
		} else if (P.changeField == 'options') {
			P.color = P.capacity = P['interface'] = P.cache = P.spinSpeed = null;
		} else if (P.changeField == 'cache') {
			P.color = P.capacity = P['interface'] = P.options = P.spinSpeed = null;
		} else if (P.changeField == 'spinSpeed') {
			P.color = P.capacity = P['interface'] = P.options = P.cache = null;
		}
	},
	resetModelListOver: function() {
		// Reset modelList based on what was moused over
		var P = ProductInfoSelector;
		if (P.overField == 'color') {
			P.capacity = P['interface'] = P.options = P.cache = P.spinSpeed = null;
		} else if (P.overField == 'capacity') {
			P.color = P['interface'] = P.options = P.cache = P.spinSpeed = null;
		} else if (P.overField == 'interface') {
			P.color = P.capacity = P.options = P.cache = P.spinSpeed = null;
		} else if (P.overField == 'options') {
			P.color = P.capacity = P['interface'] = P.cache = P.spinSpeed = null;
		} else if (P.overField == 'cache') {
			P.color = P.capacity = P['interface'] = P.options = P.spinSpeed = null;
		} else if (P.overField == 'spinSpeed') {
			P.color = P.capacity = P['interface'] = P.options = P.cache = null;
		}
	},
	restoreSelections: function() {
		// restore selctions on mouse out
		//console.log("P.restoreSelections()");
		var P = ProductInfoSelector;
		if (P.overField != null) { // check this in case user clicked before mouse out
			if (P.changeField == 'color') {
				P.color = P.saveCurrentModel.color; // set the original filter 
			} else if (P.changeField == 'capacity') {
				P.capacity = P.saveCurrentModel.capacity;
			} else if (P.changeField == 'interface') {
				P.interface = P.saveCurrentModel.interface;
			} else if (P.changeField == 'options') {
				P.options = P.saveCurrentModel.options[0].name;
			} else if (P.changeField == 'cache') {
				P.cache = P.saveCurrentModel.cache;
			} else if (P.changeField == 'spinSpeed') {
				P.spinSpeed = P.saveCurrentModel.spinSpeed;
			}
			P.overField = null;
		}
	},
	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;
				}
			}
		}
		try{P.updateSKU();}catch(e){} //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() {
		//console.log("P.currentModelList");
		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
				)
		{
			//var i = 0;
			//do {
			  modelList = P.filterModelList(
										I.releaseList[this.releaseIndex].modelList,
										P.buildModelFilter()
									);
			  //i++;
			  //console.log("whileloop "+i);
			  //if(modelList.length < 1) P.capacity = null;
			//}
			//while (modelList.length < 1 && i <= 7 );
			
		}
		//console.dir(modelList);
		return modelList;		
	},
	colorList: function(modelList) {
		//console.log("P.colorList()");
		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); });		
	},
	optionsList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return jQuery.map(n.options, function(n,i) { return (n.name); })});		
	},
	optionsList_en: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return jQuery.map(n.options_en, function(n,i) { return (n.name_en); })});		
	},
	spinSpeedList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n.spinSpeed); });		
	},
	drIdList: function(modelList) {
		return jQuery.map(modelList, function(n, i){ return (n.drProductId); });		
	},
	filterModelList: function(modelList, filterArgs) {
		//console.log("P.filterModelList()");
		var ret = [];
		//console.dir(modelList);
		OUTER:
			for (var i = 0, length = modelList.length; i < length; i++) {
				
				for (var prop in filterArgs) {
					//console.log(modelList[i][prop][0].name+" "+filterArgs[prop]+" "+prop);
					if (prop == 'options' && modelList[i].options[0]) {
						if (! (modelList[i].options[0].name && modelList[i].options[0].name == filterArgs[prop])) {
							continue OUTER;
						}
					} else if (! (modelList[i][prop] && modelList[i][prop] == filterArgs[prop])) {
						continue OUTER;
					}
				}
				ret.push(modelList[i]);
			}
		//console.log(ret);
		return ret;
	},
	buildModelFilter: function(filterOption) {
		//console.log("P.buildModelFilter()");
		var filter = {};
		var args = [ 'color', 'capacity', 'interface', 'cache', 'options', 'spinSpeed' ];
		if (filterOption == "matched") {
			//console.log("matched");
			for (var i = 0, length = args.length; i < length; i++) {
				if (ProductInfoSelector.selectionHistory[args[i]]) {
					//console.log("%s: %s", args[i], ProductInfoSelector[args[i]]);
					filter[args[i]] = ProductInfoSelector.selectionHistory[args[i]];
				}
			}
		} else {
			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(
											arrToObjForCapacity(P.capacityList(modelList)),
											false
										);
		if (P.capacity) {
			//console.log('P.capacity:'+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(
											arrToObjForCapacity(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) {
			//console.log("inside first not dontselector update");
			P.color = color;
			P.changeField = 'color';
		}
		$('#ProductColor').text(pretty_name);
		try{P.updateSKU();}catch(e){}
		if (! dont_track_selector_update)
			P.updatePulldowns();
		// Analytics hook
	},
	colorOver: 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);
		
		try{P.updateSKU();}catch(e){}
		P.updateFields();
		// Analytics hook
	},
	comparison: function(model)
    {
        var P = ProductInfoSelector;
        //var model = P.currentModel(); variable already set by updateSKU
        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;
            	options.language='DE';
            } 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);
            }
        }
    },
	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']);
		try{P.updateSKU();}catch(e){}
		P.updateFields();
		// Analytics Hook
	},
	updateInterfaceText: function(text, changeSelect) {
		$('#ProductInterface').text(text);
		if (changeSelect)
			$('select[name=interface]').selectOptions(text);
	},
	quantityChanged: function(event) {
		// console.log('qualityChanged');
		var model = ProductInfoSelector.currentModel();
		ProductInfoSelector.updateBuyLink(model);
	},
	cacheChanged: function(event) {
		// console.log('cacheChanged');
		event.preventDefault;
		var P = ProductInfoSelector;
		P.changeField = 'cache';
		P['cache'] = $(this).val();
		P.updateCacheText(P['cache']);
		try{P.updateSKU();}catch(e){}
		P.updateFields();
		// Analytics Hook
	},
	updateCacheText: function(text, changeSelect) {
		$('#ProductCache').text(text);
		if (changeSelect)
			$('select[name=cache]').selectOptions(text);
	},
	updateFields: function(modelListArg) {
		//console.log("P.updateFields()");
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		var modelList = modelListArg || P.currentModelList();

		//P.updateColor(modelList);
		P.updatePulldowns(modelList);
	},
	currentModel: function() {
		//console.group("P.currentModel()");
		// This function determines what the current active model is. It attempts to preserve any selections the user has
		// made but will give the latest click priority and reset any of the previous selections that are no longer available
		// in the selected combination
		var P = ProductInfoSelector;
		var C = ColorPicker;
		var CP = CapacityPicker;
		var IP = InterfacePicker;
		var CHP = CachePicker;
		var SP = SpinSpeedPicker;
		var OP = OptionsPicker;
		var modelList = P.currentModelList();
		//console.log(modelList);
		var matchedModel = [];
		var model = null;
		if (jQuery.isArray(modelList) && modelList.length > 0) {
			//model = modelList[0];
			
			matchedModel = P.filterModelList(modelList,P.buildModelFilter("matched"));
			//console.log(matchedModel);
			if (matchedModel.length < 1) {
				//console.group("matchedModel is null - before for loop");
				//console.log("P.selectionHistory");
				//console.log(P.selectionHistory);
				//console.log("P.selectionAttributeHistory");
				//console.log(P.selectionAttributeHistory);
				//console.groupEnd();

				if (!P.overField) {
					//console.log("no overfield");
					while (matchedModel.length < 1) {
						for (prop in P.selectionHistory) {
							if(prop == P.selectionAttributeHistory[0]) {
								//console.log(P.selectionHistory[prop]);
								P.selectionHistory[prop] = null;
								P.selectionAttributeHistory.shift();// remove first selected attribute from selectionHistory
								matchedModel = P.filterModelList(modelList,P.buildModelFilter("matched")); // filter again
								break;
							}
						} // repeat until we return a model
					}
					model = matchedModel[0];
				} else {
					model = modelList[0];	
				}
				//console.group("matchedModel is null - after for loop");
				//console.log("P.selectionHistory");
				//console.log(P.selectionHistory);
				//console.log("P.selectionAttributeHistory");
				//console.log(P.selectionAttributeHistory);
				//console.groupEnd();
			} else {
				//comment by liuxiao, for QC 1485
				//model = matchedModel[0];
				var index=0;
				if(product_type!="seagate")
				{
					//model = matchedModel[0];
					index=getLowestModel(matchedModel);
				}else
				{
					index=getHighestModel(matchedModel);		
				}
				model=matchedModel[index];
			}
		}
		//console.log("Model:");
		//console.log(model);
		//console.groupEnd();
		P.model = model;
		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.group("P.updateSKU()");
		var P = ProductInfoSelector;
		var I = ProductInfoStruct;
		
		var model = P.model;
		if (! model)
			return;

		//alert(model.modelNumber);
		 //console.log("updateSKU model");
		 //console.log(model);
		P.sku = model.modelNumber;
		
		if (P.sku) {
			$('#ProductSKU').text(P.sku);
			// changeModel(P.sku);
		}
		
		P.updateTabLinks();
		P.comparison(model); //update price spider widget parameters
		
		if (! model.drInfo || typeof(model.drInfo.error) != "undefined") {
			
			//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(); comment this line as it appears to be a dupe call
				/*$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(model);
				
				$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
						);
						
				
			}
		}
		//console.groupEnd();
	},
	getOfferTextFromOfferInstance: function(offerInstance) {
		if (! offerInstance)
			return '';
		
		if (offerInstance.salesPitchKey1) {
			//return '<p>' + offerInstance.salesPitchKey1 + '</p>';
			return '<p class="special">' + offerInstance.salesPitchKey1 + '</p>';
		}
		
		return '';
	},
	updateBuyLink: function(model) {
		//console.log("P.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) {
		//console.log("P.updateColor");
		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();
		//console.dir(model);
		//if (model) {
			//ColorPicker.selectColor(model.color);
		//}
	},
	updatePulldowns: function(modelListArg) {
		//console.group("P.updatePulldowns");
		var P = ProductInfoSelector;
				
		//console.log("updatePulldowns modelListArg");
		//console.log(modelListArg);
		
		//console.log("updatePulldowns currentModelList");
		//console.log(P.currentModelList());
		
		var modelList = modelListArg || P.currentModelList();
		var currentModel = P.currentModel();
		//console.log(currentModel);
		
		//console.log("Saved Attributes: "+P.color+"|"+P.capacity+"|"+P.interface+"|"+P.cache+"|"+P.options+"|"+P.spinSpeed);
		
		//P.updateColor();
		ColorPicker.updateColors(P.colorList(modelList),currentModel);
		CapacityPicker.updateCapacity(modelList,currentModel);
		InterfacePicker.updateInterface(modelList,currentModel);
		OptionsPicker.updateOptions(modelList,currentModel);
		CachePicker.updateCache(modelList,currentModel);
		SpinSpeedPicker.updateSpinSpeed(modelList,currentModel);
		
		//console.log("Saved Attributes: "+P.color+"|"+P.capacity+"|"+P.interface+"|"+P.cache+"|"+P.options+"|"+P.spinSpeed);
		
		//console.log("P.selectionHistory:");
		//console.log(P.selectionHistory);
		//console.log("P.selectionAttributeHistory:");
		//console.log(P.selectionAttributeHistory);
		//console.groupEnd();
	},

	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;
		}
	},
	buildToolTip: function(modelList) {
		var P = ProductInfoSelector;
		var optionsTitle = localeStrings['options'];
		var toolTipContent = "<h3>"+optionsTitle+"</h3><ul>";
		var toolTipCount = 0;
		var optionsData = jQuery.map(
			modelList, 
			function(model, modelIndex){ 
				return model.options;
			});

		//console.log(optionsData);
		optionsData = optionsArrayUnique(optionsData).sort();
		//console.log(optionsData);
		//comment by liuxiao on Oct 29
		//optionsData = optionsData.sort(sortByOptionName);
		//console.log(optionsData);
		
		//QC 1634 sort option tooltips based on option name
		optionsData=sortOptionsData(optionsData,P.options_name);
		
		$.each(optionsData, function(optionsIndex, option) {
			
			if(option!=null&&option!="undefined"){
				if (option.tooltip) {
					toolTipContent += "<li>"+option.name+" &mdash; "+option.tooltip+"</li>";
					toolTipCount++;
				}
			}
		});
		toolTipContent += "</ul>";

		if (toolTipCount > 0) {
			$('#optionsToolTip').qtip(
			{
				content: toolTipContent,
				position: {
					corner: {
						target: 'topRight',
						tooltip: 'bottomLeft'
					}
				},
				style: { 
					width: 300,
					padding: 5,
					background: '#FFFFFF',
					color: 'black',
					border: {
						width: 2,
						color: '#FF9933'
					},
					tip: 'bottomLeft'
				}
			});
		} else {
			$('#optionsToolTip').remove();	
		}
	}
};

function sortByOptionName(a, b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function optionsArrayUnique(arrayOriginal) {
		var uniqueArray = new Array();
		uniqueArray[0]=arrayOriginal[0];
		for(var i=0;i<arrayOriginal.length;i++)
		{
			var flag = true;
			for(var j=0;j<uniqueArray.length;j++)
			{
				if(uniqueArray[j].name==arrayOriginal[i].name) flag = false;
			}
			if(flag==true) uniqueArray.push(arrayOriginal[i]);
		}
		return uniqueArray;
 }
 
function arrayUnique(arrayOriginal) { // removes duplicate values from array
    var uniqueArray = new Array();
    uniqueArray[0]=arrayOriginal[0];
    for(var i=0;i<arrayOriginal.length;i++)
    {
      var flag = true;
      for(var j=0;j<uniqueArray.length;j++)
      {
        if(uniqueArray[j]==arrayOriginal[i]) flag = false;
      }
      if(flag==true) uniqueArray.push(arrayOriginal[i]);
    }
    return uniqueArray;
}

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;
}

function arrToObjForCapacity(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++) {
		var temp=arr[i];
		temp=temp.replace(new RegExp(" ", 'g'), " ");
		ret[arr[i]] = temp;
		
	}
	
	return ret;
}

function arrToObjForCapacityOrderByType(arr,product_type) {
	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{
				if(product_type=="seagate"){
					return b1-a1;
				}else{
					return a1-b1;
				}
				
			}
		}
	);
	for (var i = 0, length = arr.length; i < length; i++) {
		var temp=arr[i];
		temp=temp.replace(new RegExp(" ", 'g'), " ");
		ret[arr[i]] = temp;
		
	}
	
	return ret;
}

//developed by liuxiao, to sort cache & spin spedd as per Core product
function arrToObjForCacheOrder(arr) {
	var ret = {};
	arr.sort(
		function(a,b){
			if(a==b){
				return 0;
			}else
			{
				a=a.replace("MB","");
				a=a.replace(" ","");
				a=a.replace(",","");
				b=b.replace("MB","");
				b=b.replace(" ","");
				b=b.replace(",","");
				if(!isNaN(a) && !isNaN(b))
				{
					return b-a;
				}
			}
	    }
	);
	
	for (var i = 0, length = arr.length; i < length; i++) {
		var temp=arr[i];
		temp=temp.replace(new RegExp(" ", 'g'), " ");
		ret[arr[i]] = temp;
		
	}
	
	return ret;
}
//end by liuxiao


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,
				videoSmoothing: true
				},
			params: { wmode: 'transparent', scale:'noScale', salign:'tl', menu:'false', allowScriptAccess:'always', videoSmoothing:'true' },
			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();
	
	$('#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));
	}
	if ($('.productInfoSelector').length > 0) {
		ProductInfoSelector.updateSKU();
	}
	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();
	
	/* clickable div for promoTile */
	$(".divLink").click(function(){
	      window.location = $(this).find("a:first").attr("href")
	   });
	
	// 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
	                      });
	}

	// SearchRev Tracking
	$(".focusBoxRight").find("span").click(function () { 
		//comparison shop click
		var axel = Math.random() + "";
		var num = axel * 1000000000000000000;
		var imageTagG=new Image();
		//added by liuxiao, as per QC 1630, the src is different between en-us and non en-us
		var this_locale = getLocale();
		this_locale=this_locale.toLowerCase();
		if(this_locale=="en-us" || this_locale=="en_us")
		{
			imageTagG.src="http://www.googleadservices.com/pagead/conversion/1050228892/?label=21OYCMjr1wEQnPHk9AM&amp;guid=ON&amp;script=0";
		}else
		{
			imageTagG.src="http://www.googleadservices.com/pagead/conversion/1009503178/?label=6pdaCN722AEQypev4QM&amp;guid=ON&amp;script=0";
		}
		//end by liuxiao
		var imageTagSR=new Image();
		imageTagSR.src="https://s1.srtk.net/www/delivery/ti.php?trackerid=1048&_sr_actiontype=altorder&cb=" + num;
    });
	$("#focusBoxContainer_purchaseContainer_001").find("a").click(function (event) { 
		//add to cart click
		event.preventDefault();
		var imageTagG=new Image();
		imageTagG.src="http://www.googleadservices.com/pagead/conversion/1050228892/?label=PfyuCMDs1wEQnPHk9AM&amp;guid=ON&amp;script=0";
		var imageTagSR=new Image();
		imageTagSR.src="https://s1.srtk.net/www/delivery/ti.php?trackerid=1048&cb=866929480&_sr_actiontype=action";
		imageTagSR.onload = setTimeout("addToCartURL()",500);
    });
});

function addToCartURL() {
	//redirects to add to cart url - req'd for tracking code
	top.location.href=$("#focusBoxContainer_purchaseContainer_001").find("a").attr("href");
}

//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;
		}
  }  

  /*Added by Hua Shuai at 2010-7-22 for QC 1539. This method is to convert single quote to &#146; , convert double quote to &#148; and convert backslash to &#92;*/
  
  function replaceSpecialCharacter(source){
	var results="";
	var singlequoteString="&#146;";
	var doublequoteString="&#148;";
	var backslashString="&#92;";
	for(var i=0;i<source.length;i++){
		if(source.charCodeAt(i)=="8217"){
			results+=singlequoteString;
		}else if(source.charCodeAt(i)=="8221"){
			results+=doublequoteString;
		}else if(source.charCodeAt(i)=="92"){
			results+=backslashString;
		}else{
			results+=source.charAt(i);
		}
		
	}
	return results;
}

function getHighestModel(matchedModel)
{
	if(matchedModel.length==1)
	{
		return 0;
	}
	
	var index=0;
	var arrMaxCapacity=new Array();
	var arrNoneFeature=new Array();
	var arrMaxCache=new Array();
	var arrMaxSpinspeed=new Array();
	var pos=0;
	var P = ProductInfoSelector;
	/*
	for(index=0;index<matchedModel.length;index++)
	{
		if((matchedModel[index].cache==P.maxcache || P.maxcache==null) && (matchedModel[index].capacity==P.maxcapacity || P.maxcapacity==null) && (matchedModel[index].spinSpeed==P.maxspinspeed || P.maxspinspeed==null))
		
		{
			for(var jj=0;jj<matchedModel[index].options.length;jj++)
			{
				if(matchedModel[index].options[jj].name=="None")
				{
					model=matchedModel[index];
					break;
				}
			}
			
		}
	}
	*/
	
	//filter capacity, pick up models which have max capacity, and save index to arrMaxCapacity
	pos=0;
	if(P.maxcapacity!=null)
	{
		for(var i=0;i<matchedModel.length;i++)
		{
			if(matchedModel[i].capacity==P.maxcapacity)
			{
				arrMaxCapacity[pos]=i;
				pos=pos+1;
			}
		}
	}else
	{
		for(var i=0;i<matchedModel.length;i++)
		{
			arrMaxCapacity[i]=i;
		}
	}
	
	if(arrMaxCapacity.length==1)
	{
		//only one model has highest capacity
		return arrMaxCapacity[0];
	}
	
	if(pos==0)
	{
		for(var i=0;i<matchedModel.length;i++)
		{
			arrMaxCapacity[i]=i;
		}
	}
	
	//filter feature, if a model has 'None' feature, save index to arrNoneFeature
	pos=0;
	for(var i=0;i<arrMaxCapacity.length;i++)
	{
		index=arrMaxCapacity[i];
		for(var jj=0;jj<matchedModel[index].options.length;jj++)
		{
			if(matchedModel[index].options[jj].name in { "None":1, "Ninguno":1, "Aucun":1, "Brak":1, "Keine":1, "Nessuna":1, "Ninguno":1, "Yok":1, "нет":1, "なし":1, "无":1, "無":1, "해당 없음":1 })
			{
				arrNoneFeature[pos]=index;
				pos=pos+1;
				break;
			}
		}
	}
	
	if(arrNoneFeature.length==1)
	{
		//in highest capacity models, only one has None Feature
		return arrNoneFeature[0];
	}
	
	if(pos==0)
	{
		//there is no None feature, so all arrMaxCapacity will be copied to arrNoneFeature
		//in this case, we will ignore feature=='None' since there is no None feature
		arrNoneFeature=arrMaxCapacity;
	}
	
	//filter cache, if a model has a max cache, save index to arrMaxCache
	pos=0;
	if(P.maxcache!=null)
	{
		
		for(var i=0;i<arrNoneFeature.length;i++)
		{
			index=arrNoneFeature[i];
			if(matchedModel[index].cache==P.maxcache)
			{
				//since max cache is found, then index is the model which has highest capacity, none feature, and highest cache
				arrMaxCache[pos]=index;
				pos=pos+1;
			}
		}
	}
	
	if(arrMaxCache.length==1)
	{
		//in highest capacity models, with None Feature, only one has max cache
		return arrMaxCache[0];
	}
		
	if(pos==0)
	{
		//there is no model has max cache, so all models(have max capacity and None feature) will compare spin speed
		arrMaxCache=arrNoneFeature;
	}
	
	if(arrMaxCache.length==0)
	{
		index=arrNoneFeature[0];
	}else if(arrMaxCache.length==1)
	{
		index=arrMaxCache[0];
	}else
	{
		//check spin speed
		pos=0;
		
		for(var i=0;i<arrMaxCache.length;i++)
		{
			index=arrMaxCache[i];
			//modified by Liu Xiao when fixing QC 1708
			//if(matchedModel[index].cache==P.maxspinspeed)
			if(matchedModel[index].spinSpeed==P.maxspinspeed)
			{
				pos=pos+1;
				break;
			}
		}
		
		if(pos==0)
		{
			//no one has highest spinspeed, the first one will be returned
			index=arrMaxCache[0];
		}
	}
	
	return index;
}

function getLowestModel(matchedModel)
{
	if(matchedModel.length==1)
	{
		return 0;
	}
	
	var index=0;
	var arrMinCapacity=new Array();
	var pos=0;
	var P = ProductInfoSelector;
	
	pos=0;
	if(P.maxcapacity!=null)
	{
		for(var i=0;i<matchedModel.length;i++)
		{
			if(matchedModel[i].capacity==P.maxcapacity)
			{
				arrMinCapacity[pos]=i;
				pos=pos+1;
			}
		}
	}else
	{
		return 0;
	}
	
	if(arrMinCapacity.length>=1)
	{
		//only one model has highest capacity
		return arrMinCapacity[0];
	}
	
	return 0;
	
}

function arraySortUniqueForOptions(arrayOriginal, arrayOriginal_en)
{
	if(arrayOriginal==null || arrayOriginal_en==null || arrayOriginal.length<2)
	{
		ProductInfoSelector.options_name=arrayOriginal;
		return arrayOriginal
	}
	
	var uniqueArray = new Array();
	var uniqueArray_en =  new Array();
	uniqueArray[0]=arrayOriginal[0];

  	uniqueArray_en[0]=arrayOriginal_en[0];
  	
  	//unique
  	for(var i=0;i<arrayOriginal_en.length;i++)
    {
        var flag = true;
        for(var j=0;j<uniqueArray_en.length;j++)
        {
          if(uniqueArray_en[j]==arrayOriginal_en[i]) flag = false;
        }
        if(flag==true) 
    	{
      		uniqueArray_en.push(arrayOriginal_en[i]);
      		uniqueArray.push(arrayOriginal[i]);
    	}
    }
  	
  	//sort
  	for(var i=0;i<uniqueArray_en.length;i++)
  	{
  		for(var j=i;j<uniqueArray_en.length;j++)
  		{
  			if(uniqueArray_en[i]>uniqueArray_en[j] || uniqueArray_en[i].toLowerCase() == "none")
  			{
  				var t=uniqueArray_en[i];
  				uniqueArray_en[i]=uniqueArray_en[j];
  				uniqueArray_en[j]=t;
  				
  				t=uniqueArray[i];
  				uniqueArray[i]=uniqueArray[j];
  				uniqueArray[j]=t;
  			}
  		}
  	}
  	
  	return uniqueArray;
    
}

//QC 1634
function sortOptionsData(optionsData,options_name)
{
	if(optionsData==null || options_name==null || optionsData.length<2)
    {
          return optionsData;
    }
	
	var newoptionsData=new Array(optionsData.length);
	var i=0;

  	for(i=0;i<options_name.length;i++)
  	{
  		for(var j=0;j<optionsData.length;j++)
  		{
  			if(optionsData[j].name==options_name[i])
  			{
  				newoptionsData[i]=new Array(2);
  				newoptionsData[i][0]=optionsData[j].name;
  				newoptionsData[i][1]=optionsData[j].tooltip;
  				break;
  			}
  		}
  	}
  
  	i=0;
  	
  	for(i=0;i<newoptionsData.length;i++)
  	{
  		optionsData[i].name=newoptionsData[i][0];
  		optionsData[i].tooltip=newoptionsData[i][1];
  	}
  	
	return optionsData;
}

//QC 1708
function sortSpinSpeed(arrayOriginal) {
	if(arrayOriginal==null || arrayOriginal.length<2)
	{
		return arrayOriginal;
	}
	
	var uniqueArray = new Array();
	var spinspeedArray = new Array();
	var flag = true;
	var index=1;
	uniqueArray[0]=arrayOriginal[0];
	for(var i=0;i<arrayOriginal.length;i++)
	{
		flag = true;
		for(var j=0;j<uniqueArray.length;j++)
		{
			if(uniqueArray[j]==arrayOriginal[i]) flag = false;
		}
		if(flag==true) 
		{
			uniqueArray[index]=arrayOriginal[i];
			index++;
		}
	}
	
	//sort
	for(var i=0;i<uniqueArray.length;i++)
	{
		for(var j=1;j<uniqueArray.length+1;j++)
		{
			if(uniqueArray[i]<uniqueArray[j])
			{
				var temp=uniqueArray[i];
				uniqueArray[i]=uniqueArray[j];
				uniqueArray[j]=temp;
			}
		}
	}
	/*
	index=0;
	for(var i=0;i<uniqueArray.length;i++)
	{
		spinspeedArray[index]=uniqueArray[i];
		index++;
	}*/
	return uniqueArray;
}
