// Store2 - ATA 
// Item UI
// jBlossom - Creori, Inc. - 2008

// OPTION / VALUE SELECTORS

// define console.log for IE or for FF if firebug is not installed.
/*if(navigator.userAgent.toLowerCase().indexOf("msie") != -1 || typeof console == 'undefined') {
	console = new Object();
	//console.log = function() {return;}
}*/

showValue = function(elem) {
	//console.log('entering showValue() - elem: ', elem);
	var option = $(elem).up('.option_dimension');
	var optionGUID = $(option).readAttribute('optionGUID');
	var label = ' : ' + elem.title;

	if ($(elem).up('.option').hasClassName('disabled')) {
		label += ' <span class="outOfStockNote">(out of stock)</span>';
		//$('addToCartButton').disable().src = '/images/site/btn_ylw_outofstock_off.gif';
	}
	
	option.down('.option_dimension_selected').innerHTML = label;

	checkOption(elem);
}

// ov onMouseOut
hideValue = function(elem) {
	//console.log('entering hideValue() - elem: ', elem);
	var option = $(elem).up('.option_dimension');
	//var item = option.up('.item');
	//var firstOptionValue = option.up('.item').down('.option_dimension').down('.on');
	var optionGUID = option.readAttribute('optionGUID');
	var active = option.select('.on');
	//console.log(firstOptionValue, 'firstOptionValue');
	if (active.length) {
		option.down('.option_dimension_selected').innerHTML = ' : ' + active[0].down().title;
		//console.log(selectedItemImages, 'selectedItemImages-q')
		var activeValue = active[0].down('.value');
		//hilAvail('', activeValue);
		checkOption(activeValue);
		//setImages(selectedItemImages);
		var activeValue = eval(activeValue.readAttribute('ov'))[1];
		var itemPointSessionInventory = 0; //getItemPointSessionInventory(item.readAttribute('itemGUID'), activeValue);
		var currQty = $F('quantity') - itemPointSessionInventory;
		
		//console.log('currQty', currQty);
		
		if (currQty) {
			//console.log('setting btn_pnk_addtobasket 1');
			$('addToCartButton').src = '/images/site/btn_pnk_addtobasket.gif'; //'/images/site/btn_pnk_add' + currQty + 'items.gif'; //enable().
		}
		else
			$('addToCartButton').src = '/images/site/btn_ylw_addtobasket.gif'; //'/images/site/btn_ylw_outofstock_off.gif'; //disable().
	}
	else {
		option.down('.option_dimension_selected').innerHTML = '';
	}
}

// ov onClick
setValue = function (elem, partID) {
	//console.log('entering setValue() - ', elem, partID);
	if (!elem || !items)
		return false;

	if (!partID)
		partID = 0;

	var item = elem.up('.item');
	var ic = item.readAttribute('ic');
	var option = elem.up('.option_dimension');
	var currOV = eval(elem.readAttribute('ov'));
	var optionGUID = currOV[0]
	var valueGUID = currOV[1];
	var valueShell = $(elem).up('.option');
	var haveValidPoints = false;
	//var selectedQty = $F(item.down('#quantity'));
		
	//selectedQty = !isNaN(selectedQty) ? selectedQty : 1;

	if (!valueShell.hasClassName('disabled')) {
		items[ic].get('options').set(optionGUID, valueGUID); // Set hidden field
		option.select('.option').each(function(item) { // Remove highlight from all the values
			item.removeClassName('on');
		});
		
		option.down('.option_dimension_selected').innerHTML = ' : ' + elem.title; //Update Display
		valueShell.addClassName('on');// Highlight checked value
		var newItemImages = getImages([[optionGUID, valueGUID]]);
		if (newItemImages.length)
			selectedItemImages = newItemImages;
	}
	else {
		//$('optionGUID_' + optionGUID).value = ''; // clear hidden field if we clicked on an invalid option.
		//items[ic].get('options').set(optionGUID, '');
		return false;
	}

	//setQuantitySelect(ppt.Data);

	var currPoint = setItemPointField(item, partID); // Sets the hidden form field with the point of the selected option/values.
	if (currPoint.length) {
		currPoint = currPoint[0];
		//console.log('HERE', currPoint, typeof currPoint);
		//console.log(pointInventory, availableInventoryGUID);
		var pointInventory = findPointProperty(currPoint, availableInventoryGUID);
		//console.log("pointInventory", pointInventory);
		pointInventory = pointInventory.Data;
		
		if (typeof currPoint == 'object') {
			haveValidPoints = true;
			item.select('.itemPointField').each(function (field) {if ($F(field).length == 0) {haveValidPoints = false; return false; }});
		}
	}
	
	//console.log('haveValidPoints', haveValidPoints);
	if (haveValidPoints) {
		//console.log('qqq');

		var itemPointSessionInventory = getItemPointSessionInventory(item.readAttribute('itemGUID'), currPoint.pointGUID);
		var selectedQty = setQuantitySelect(pointInventory, itemPointSessionInventory);

		//console.log("currPoint", currPoint, "selectedQty", selectedQty);
		//console.log('pointInventory', pointInventory, 'itemPointSessionInventory', itemPointSessionInventory);
		
		if (selectedQty) {
			$('errorMessage').hide();
			//console.log('setting btn_pnk_addtobasket 2');
			updatePrices(currPoint);
			$('addToCartButton').src = '/images/site/btn_pnk_addtobasket.gif'; //'/images/site/btn_pnk_add'+selectedQty+'items.gif'; //enable().
		}
		else
			$('addToCartButton').src = '/images/site/btn_ylw_addtobasket.gif'; //'/images/site/btn_ylw_outofstock_off.gif'; //disable().
	}
	else {
		//console.log('nnn');
		$('addToCartButton').src = '/images/site/btn_ylw_addtobasket.gif'; //'/images/site/btn_ylw_selectoptions_off.gif'; //disable().
	}
}

checkOption = function(elem) {
	//console.trace();
	if (!elem || !items) {
		return false;
	}
	var opt = "";
	var itm = elem.up('.item');
	var ic = itm.readAttribute('ic');
	var numOptions = items[ic].get('numOptions'); //$F(item.down('#numOptions'));
	var optionValues = items[ic].get('options'); // get the values for all the item's options

	var currOV = eval(elem.readAttribute('ov')); //eval('(' + elem.readAttribute('ov') + ')');
	var currOption = $(elem).up('.option_dimension'); // get the current option.
	var optionGUID = currOV[0]; //option.readAttribute('optionGUID');
	var matrixPoint = [];
	//var opts = elem.up('.item').select('.option_dimension'); //$$('.option_dimension'); // get all the item's options
	//console.log('optionGUID', optionGUID);

	//updatePrices(matrixPoint);

	//console.log('opts', opts);
	/*var otherOpts = opts;
	var numOpts = otherOpts.length;
	for (var i = 0; i < numOpts; i++) {
		if (otherOpts[i].readAttribute('optionGUID') == optionGUID) {
			otherOpts.splice(i, 1);
			break; // We assume there's only one current option.
		}
	}*/
	//console.log('otherOpts', otherOpts);
	//console.log('optionValues', optionValues);

	//opts.each(function (opt) { if (opt.readAttribute('optionGUID') == optionGUID) { opt.splice(2, 1); return; } }); //{ otherOption = opt; return; }// Get the "OTHER" options.
	//for (i = 0; i < numOptions; i++) {
	optionValues.each(function (opt) {
		if (opt[0] == optionGUID)
			return false; // skip over current option

		//console.log('opt', opt);
		var otherOptionValues = new Array();
		var otherOptions = itm.select('div.option_dimension'); //#dimension_' + opt[0] //'div[itemPart, id = "#dimension_' + opt[0] + '"]'
		//console.log(otherOptions.length, 'otherOptions');
		// merge all the values to check them all at once if it's a multipart item.
		otherOptions.each(function (otherOpts) {
			if (otherOpts.readAttribute('optionGUID') != optionGUID)
				otherOptionValues = otherOptionValues.concat(otherOpts.select('.value'));
		});

		//var otherOption = itm.down('[optionguid]');
		//console.log(otherOptionValues, 'otherOptionValues');
		
		//console.log('otherOptionValues', otherOptionValues);
		/*NOT SURE WHY WE WERE DOING THIS: if(opt[1].length) {
			//console.log('1');
			currOption.select('.option').each(function(value) { // Remove highlight from all the values
				//console.log(itm.down().title);
				value.removeClassName('disabled');
			});
		}*/
		
		//alert(opt.toString());
		//console.log(otherOptionValues, "otherOptionValues");
		if (otherOptionValues.length) {

			otherOptionValues.each(function (val) { // loop over the values of this "OTHER" option
				var thisOV = eval(val.readAttribute('ov'));//eval('$(' + val.readAttribute('ov') + ')');
				var matrixPoint = findByOptionValues([thisOV, currOV]); // JSB: Needs to be expanded to work with > 2 options.
				//console.log(thisOV, 'thisOV');
				//console.log(currOV, 'currOV');
				//alert(typeof matrixPoint);
				//console.log('found! matrixPoint: ', matrixPoint);
				var vl = $('value_' + thisOV[1]);
				if (matrixPoint.length) {
					matrixPoint = matrixPoint[0];
					var availableInventory = findPointProperty(matrixPoint, availableInventoryGUID);

					var itemPointSessionInventory = getItemPointSessionInventory(itm.readAttribute('itemGUID'), matrixPoint.pointGUID);


					//console.log(vl, 'checkOption:thisOV==', thisOV, '     availableInventory==', availableInventory.Data);
					if (vl.up().hasClassName('on'))
						updatePrices(matrixPoint);

					//console.log('vl', vl);
					//vl.update(availableInventory.Data);//vl.innerHTML + ' ' + 
					//$('qtyAvail').update(availableInventory.Data);
					//setQuantitySelect(availableInventory.Data);
					//console.log(availableInventory);
					if (availableInventory.Data - itemPointSessionInventory > 0) {
						vl.up().removeClassName('disabled');
						//setQuantitySelect(availableInventory.Data);
						//var selectedQty = setQuantitySelect(availableInventory.Data, itemPointSessionInventory);
					}
					else {
						vl.up().addClassName('disabled');
						//console.log(vl, 'disabled 1');
					}
					
				}
				else {
					vl.up().addClassName('disabled');
					//console.log(vl, 'disabled 2');
				}
				//console.log('--------------');
			});
		}
		else { //No values to select - we're assuming it's a single value - use it.
			var thisOV = opt;
			var matrixPoint = findByOptionValues([thisOV, currOV]); // JSB: Needs to be expanded to work with > 2 options.
			if (matrixPoint.length) {
				//var ppt = findPointProperty(matrixPoint[0], availableInventoryGUID);
				//console.log('thisOV(2)==', thisOV, '     ppt==', ppt.Data);
				//setQuantitySelect(ppt.Data);
				//var retailPrice = findPointProperty(matrixPoint[0], retailPriceGUID);
				//console.log('rpt', rpt.Data);
				updatePrices(matrixPoint);
				//console.log('vl', vl);
				//vl.update(ppt.Data);//vl.innerHTML + ' ' + 
				//$('qtyAvail').update(ppt.Data);
				//setQuantitySelect(ppt.Data);
				//console.log(ppt);
				//if (ppt.Data > 0)
					//console.log('have inv');
			
			}
		}
		//console.log('================');
	}); // End looping over other options

	/*ov = elem.readAttribute('ov');
	//console.log(ov, 'ov');
	eov = [eval(ov)];
	//console.log(eov, 'eov');*/
	itemImages = getImages([currOV]);
	//console.log(currOV, 'currOV-x');
	//console.log(itemImages, 'itemImages-x');
	if (itemImages.length) {
		//console.log(itemImages.length, 'itemImages.length');
		setImages(itemImages);
	}
}

hasValidPoints = function(item) {
	var haveValidPoints = true;
	item.select('.itemPointField').each(
		function (field) {
			/*console.log('hasValidPoints', field, $F(field).length, $F(field));*/
			if ($F(field).length == 0) {
				haveValidPoints = false;
				return false;
			}
		}
	);
	return haveValidPoints;
}

// add to basket onClick
preSubmit = function (btn) {
	var item = btn.up('.item');
	var haveValidPoints = hasValidPoints(item);
	var multiPartItem = new Boolean(item.readAttribute("multiPartItem") == 'true' ? true : false);
	
	if (haveValidPoints)
		$('errorMessage').hide();
	else {
		//console.log('multiPartItem', multiPartItem, multiPartItem == true ? 'a' : 'b');
		if (multiPartItem == true)
			$('errorMessage').update("Please select a size for both the top and bottom before adding to your bag.");
		else
			$('errorMessage').update("Please select a color and size before adding to your bag.");
		$('errorMessage').hide().appear({ duration: 0.5 });
	}
	
	//console.log('haveValidPoints', haveValidPoints);
	return haveValidPoints;
	//return false;
}

getItemPointSessionInventory = function(itemGUID, pointGUID) {
	//console.log('getItemPointSessionInventory', itemGUID, pointGUID);

	if (!itemSessionInventory)
		return false;
	
	if (!pointGUID)
		pointGUID = itemGUID;
		
	var inv = $(itemSessionInventory)[itemGUID][pointGUID];
	if (!inv)
		inv = 0;
	return inv;
}

setItemPointField = function(item, partID) {
	if (!items)
		return false;
	if (!partID)
		partID = 0;
	//console.log(partID, 'partID');
	var ic = item.readAttribute('ic');
	var numOptions = items[ic].get('numOptions'); //$F(item.down('#numOptions'));
	//var optionValues = item.select('.optionValue'); // get the hidden fields for all options
	var optionValues = items[ic].get('options'); // get the values for all the item's options
	var itemPointField = item.down('#itemPointField_' + partID);
	var selectedQty = $F(item.down('#quantity'));
	var selectedOVs = [];
	var orderItemHash = new Hash();
	var haveAll = false;
	//console.log(itemPointField, 'itemPointField');
	if (!itemPointField)
		return false;
	//console.log(optionValues, numOptions);
	if (optionValues.keys().length == numOptions) { // If we have as many hidden fields as options
		haveAll = true;
		optionValues.each( function (ov) { // Check to see if all fields have values.
			//console.log('ov', ov, ov[1]);
			if (haveAll && ov[1].length)
				selectedOVs.push(ov);
			else
				haveAll = false;
		} );
	}
	//orderItemHash = {itemGUID: items[ic].get('itemGUID'), quantity: selectedQty, optionValues: selectedOVs};
	orderItemHash.set('itemGUID', items[ic].get('itemGUID'));
	orderItemHash.set('quantity', selectedQty);
	orderItemHash.set('optionValues', selectedOVs);

	//console.log('selectedOVs', orderItemHash);
	if (haveAll) {
		point = findByOptionValues(selectedOVs);
		//console.log('point', point);
		itemPointField.value = orderItemHash.toJSON();
		return point;
	}
	itemPointField.value = "";
	return false;
}

findByOptionValues = function(optionValues, type) {
	var points = [];
	var pointGUID = "";
	var matrixPoint = "";
	var found = true;

	if (typeof type == 'undefined')
		type = 'inventory';
	
	if (typeof optionValues == 'string')
		optionValues = eval('(' + optionValues + ')');
	
	if(type == 'image') {
		var matrix = itemImageMatrix;
		var matrixPoints = imageMatrixPoints;
	}
	else {
		var matrix = itemInventoryMatrix;
		var matrixPoints = inventoryMatrixPoints;
	}

	if (typeof matrix == 'undefined') {
		alert('matrix not loaded');
		return false;
	}

	//console.log('optionValues', optionValues);
	//console.log('matrixPoints.length', matrixPoints.length);
	//console.log('matrix', matrix);
	for (var i = 0; i < matrixPoints.length; i++) {
		pointGUID = matrixPoints[i];
		matrixPoint = matrix[pointGUID];
		found = true;
		for (var j = 0; j < optionValues.length; j++) {
			//console.log(optionValues[j][0] + ' : ' + optionValues[j][1]);
			if(matrixPoint.parents[optionValues[j][0]] && matrixPoint.parents[optionValues[j][0]] == optionValues[j][1]) {
				found = found && true;
			}
			else {
				found = found && false;
			}
		}
		//console.log('found', found);
		//console.log('matrixPoint', matrixPoint);
		
		if (found) {
			points.push(matrixPoint);
		}
	}
	//console.log('points', points);
	return points;
}

findPointProperty = function(point, propertyTypeGUID) {
	var property = false;
	//console.log($H(point.properties), 'kk');
	//$H(point.properties).each(function (pair) { console.log(pair.value.TypeGUID, propertyTypeGUID, pair.value.TypeGUID == propertyTypeGUID); if (pair.value.TypeGUID == propertyTypeGUID) property = pair.value; console.log(property); return true;});
	
	for (propertyGUID in point.properties) {
		//console.log("propertyGUID", propertyGUID, propertyTypeGUID, point.properties[propertyGUID].TypeGUID == propertyTypeGUID);
		if (point.properties[propertyGUID].TypeGUID == propertyTypeGUID) {
			property = point.properties[propertyGUID];
			//console.log("property ", property);
			break;
		}
	}
	return property;
}

getImages = function(optionValue) {
	return findByOptionValues(optionValue, 'image');
}

updateQuantity = function(elem, partID) {
	var item = $(elem).up('.item');
	var itemPointFields = new Array();
	var submitButton = $('addToCartButton');
	var selectedQty = $F(elem);
	
	var haveValidPoints = hasValidPoints(item);
	//console.log('haveValidPoints', haveValidPoints);
	selectedQty = !isNaN(selectedQty) ? selectedQty : 1;

	if (partID)
		itemPointFields.push(item.down('#itemPointField_' + partID));
	else
		itemPointFields = item.select('.itemPointField');

	if (!itemPointFields)
		return false;
	
	if (haveValidPoints) { //submitButton.readAttribute('disabled'))
		//console.log('setting btn_pnk_addtobasket 3');
		submitButton.src = '/images/site/btn_pnk_addtobasket.gif'; //submitButton.enable().src = '/images/site/btn_pnk_add'+selectedQty+'items.gif';
	}
	else
		submitButton.src = '/images/site/btn_ylw_addtobasket.gif';

	itemPointFields.each( function (itemPointField) {
		var itemPointFieldValue = $F(itemPointField);
		var selectedQty = $F(elem);
		//console.log('itemPointField ', $F(itemPointField));
		if (itemPointFieldValue.isJSON()) {
			var orderItemHash = $H(itemPointFieldValue.evalJSON(true));
			orderItemHash.set('quantity', selectedQty);
			itemPointField.value = orderItemHash.toJSON();
			//console.log('itemPointFieldValue ', itemPointFieldValue);
			//console.log('orderItemHash ', orderItemHash);
			return true;
		}
		else {
			return false;
		}
	});
}

updatePrices = function(matrixPoint) {
	//console.trace('entering updatePrices()', matrixPoint);
	var activePriceType = findPointProperty(matrixPoint, activePriceTypeGUID);
	var retailPrice = findPointProperty(matrixPoint, retailPriceGUID);
	var salePrice = findPointProperty(matrixPoint, salePriceGUID);
	//console.log('matrixPoint', matrixPoint);
	//console.log('retailPriceGUID', retailPriceGUID, 'salePriceGUID', salePriceGUID, 'activePriceType', activePriceType.Data);
	//console.log('retailPrice', retailPrice.Data, 'salePrice', salePrice.Data);
	var item = $('itemOptions').down('.item');
	var multiPartItem = new Boolean(item.readAttribute("multiPartItem") == 'true' ? true : false);
	//console.log('multiPartItem', multiPartItem);
	
	updatePrice(retailPrice.Data);
	
	//console.log((activePriceType.Data == salePriceGUID && salePrice && salePrice.Data));
	if (activePriceType.Data.toUpperCase() == salePriceGUID.toUpperCase() && salePrice && salePrice.Data) {
		//console.log('sale');
		updatePrice(retailPrice.Data);
		updateSalePrice(salePrice.Data);
	}
	else if (retailPrice.Data) { //if (multiPartItem == false) {
		//console.log('retail');
		updatePrice(retailPrice.Data);
		updateSalePrice(0);
	}
}

updatePrice = function(amount) {
	if (amount)
		$('selected_price').innerHTML = '$' + amount.toFixed(2);
		//try the prev for performance reasons //$('selected_price').update('$' + amount.toFixed(2));
}
updateSalePrice = function(amount) {
	if (amount) {
		$('selected_sale_price').innerHTML = '$' + amount.toFixed(2);
		$('sale_price').show();
		//try the prev for performance reasons //$('selected_price').update('$' + amount.toFixed(2));
		$('selected_price').setStyle({ textDecoration: 'line-through' });

	}
	else {
		$('sale_price').hide();
		$('selected_price').setStyle({ textDecoration: 'none' });
	}
}

// ITEM IMAGE DISPLAY GOODNESS
setImages = function(imagePoint) {
	//console.log(imagePoint, "imagePoint");
	if (!imagePoint.length)
		return;
	var imageCount = 4;
	var i = 0;
	var src = '';
	var propertyArray = new Array();
	var photoThumbContainer = $('alt_photos');
	currImageList = new Array();
	//$H(imagePoint[0].properties).toArray();
	//console.log(propertyArray.length, '88');
	//console.log(.sort(propertySorter), 'zzz');
	$H(imagePoint[0].properties).each(
		function (pair) { 
			//console.log(pair.value.Data);
			propertyArray.push(pair[1]);
		}
	);

	propertyArray.sort(propertySorter);
	//console.log(propertyArray, '88');

	if (propertyArray.length) {
		if (!photoThumbContainer)
			currImageList.push(propertyArray[0].Data);
		$('product_photo_img').src = imageBasePath + "/size2/" + propertyArray[0].Data;
	}
	else {
		return false;
	}

	if (photoThumbContainer) {
		photoThumbContainer.select('.alt_product_photo').each(
			function (alt_photo) {
				var altImage = $(alt_photo).down('img');
				var src = "";
				if(i < propertyArray.length) {
					src = imageBasePath + "/size4/" + propertyArray[i].Data;
					currImageList.push(propertyArray[i++].Data);
	
					//console.log(alt_photo, src);
					if (altImage) {
						altImage.src = src;
					}
					else {
						var altImage = new Image();
						altImage.src = src;
						alt_photo.appendChild(altImage);
					}
					
				}
				else {
					alt_photo.innerHTML = '<div class="alt_product_photo_frame"></div>';
				}
				
			}
		);	
	}
	
}

propertySorter = function(prop1, prop2) {
	return prop1.TypeSortOrder - prop2.TypeSortOrder;
}

swapImage = function(elem, pos) {
	//alert(typeof elem.down);
	var img = $(elem).down('img');
	pos = typeof pos == undefined ? 1 : pos;
	if (img && img.src.length) {
		$('product_photo_img').src = img.src.replace(/size4/,'size2');
		currImg = pos;
	}
}

// Sets the max value for the quantity field.
setQuantitySelect = function(count, sessionCount) {
	//console.log("count", count);
	var sel = $('quantity');
	var currQty = $F(sel);
	var submitButton = $('addToCartButton');

	//$('qtyAvail').update('In Stock:' + count + ' - In Carts:' + sessionCount + ' = Available:' + (count-sessionCount));
	
	if (sessionCount)
		count -= sessionCount;

	count = count > 7 ? 7 : count < 0 ? 0 : count;

//$('qtyAvail').innerHTML += ' [' + count + ']';

	sel.options.length = count <= 0 ? 7 : count;
	
	
	for (var i = 0; i < sel.options.length; i++) {
		sel.options[i].innerHTML = i + 1;
		sel.options[i].value = i + 1;
	}
	
	if (count)
		sel.enable();
	else
		sel.disable();

	if (!currQty)
		currQty = 1;

	var newQty = currQty > count ? count : currQty;

	sel.selectedIndex = newQty - 1;
	
	if (!submitButton.readAttribute('disabled') && currQty != newQty && newQty > 0) {
		submitButton.src = '/images/site/btn_pnk_addtobasket.gif';
	}
	else {
		submitButton.src = '/images/site/btn_ylw_addtobasket.gif';
	}
	
	return newQty;
}

isVal = function(val) {
	var matrixPoint = findByOptionValues([val.readAttribute('ov'), currOV]);
}

findByOptionValueProperty = function(optionValues, propertyTypeGUID) {
	var point = findByOptionValues(optionValues);
	return findPointProperty(point, propertyTypeGUID);
}

// SITE NAVIGATION
toggleSideBarView = function(toShow, hideOthers, path) {
	$('sideNav_' + toShow + '_header').src = path + 'btn_sideNav_' + toShow + '.gif';
	if (hideOthers) {
		$('sidenav').select('.sideNav_header').each( function(image) {
			if (image.id != 'sideNav_' + toShow + '_header' && !image.src.match("_off.gif"))
				image.src = image.src.replace(/.gif/, '_off.gif');
		} );
		$('sidenav').select('.sideNav_section').each( function (elem) {
			if (elem.id != 'sideNav_' + toShow) {
				try {
					Effect.BlindUp(elem, {duration:0.4});
				}
				catch(err){}
			}
		} );
	}
	try {
		$('sideNav_' + toShow).hide();
		if ($('sideNav_' + toShow).getStyle('display') == 'none')
			Effect.BlindDown('sideNav_' + toShow, {duration:0.4});
	}
	catch(err){}
	return;
}

// ITEM DETAIL PHOTO
popUpWin = "nowin";
popWin = function(name, file, width, height, status, resizable, scrollable) {
	var h=height;
	var w=width;
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',status='+status+',resizable='+resizable+',scrollbars='+scrollable;
	popUpWin = window.open( file , name, winprops );
	if (popUpWin)
		popUpWin.focus();
	return popUpWin;
}

closePopUp = function() {
	if( popUpWin != "nowin" ) {
		if( !popUpWin.closed ) {
			popUpWin.close();
		}
	}
}

showPasswordPopup = function(url) {
	popWin('passwordPopup', url, 380, 400, 0, 0, 0);
}
showSizePopup = function(itemBrandGUIDs) {
	popWin('sizePopup', '/?event=store.item.showSizing&itemBrandGUIDs=' + itemBrandGUIDs, 380, 405, 0, 0, 0);
}
showBigImage = function(elem) {
	var imgName = $(elem).down('img').src.replace(/size2/,"size1");
	popWin('bigimage', '/images/showImg.cfm?imgName=' + imgName, 500, 650, 0, 0, 0);
}
showBigImages = function(images, selected, itemName, imagePath) {
	var images = encodeURIComponent(images.toString());
	itemName = encodeURIComponent(itemName);
	if (typeof imagePath != 'undefined')
		bigImages = popWin('bigImages', '/images/showImg.cfm?images=' + images + '&selected=' + selected + '&itemName=' + itemName + '&imagePath=' + imagePath, 500, 650, 0, 0, 0);
	else
		bigImages = popWin('bigImages', '/images/showImg.cfm?images=' + images + '&selected=' + selected + '&itemName=' + itemName, 500, 650, 0, 0, 0);
	if(bigImages)
		bigImages.focus();
}

/* USER ACCOUNT FUNCTIONS */

setAddressDefault = function (input, url) {
	var userGUID = input.getAttribute("userGUID");
	var addressGUID = input.getAttribute("addressGUID");
	//console.log(addressGUID, userGUID);
	if (!userGUID.length || !addressGUID.length)
		return false;

	new Ajax.Request(url, {
		method: 'get',
		parameters: { userGUID: userGUID, addressGUID: addressGUID },
		onSuccess: function(transport) {
			if (transport.responseText == 'true') {
				if (url.indexOf('illing') > 0) {
					new Effect.Highlight('defaultBillingLabel_' + addressGUID);
					$('statusBar').hide().update('Default billing address set.');
				}
				else if (url.indexOf('hipping') > 0) {
					new Effect.Highlight('defaultShippingLabel_' + addressGUID);
					$('statusBar').hide().update('Default shipping address set.');
				}
			}
			else {
				if (url.indexOf('illing') > 0)
					$('defaultBilling_' + addressGUID).checked = false;
				else if (url.indexOf('hipping') > 0)
					$('defaultShipping_' + addressGUID).checked = false;
				$('statusBar').hide().update("There was an error saving your selection.");
			}
			new Effect.Appear($('statusBar'), {duration: 0.5});//, afterFinish:hideStatus, from: 0.0, to: 0.7, afterFinish:false 

		},
		onFailure: function (transport) {
			//$('statusBar').update(transport.responseText);
			if (url.indexOf('illing') > 0)
				$('defaultBilling_' + addressGUID).checked = false;
			else if (url.indexOf('hipping') > 0)
				$('defaultShipping_' + addressGUID).checked = false;
		}
	});
	return true;
}

hideStatus = function () {
	new Effect.Fade($('statusBar'), {duration: 2});
}

setDefaultBillingAddress = function (input) {
	var url = "/?event=user.address.setDefaultBilling";
	setAddressDefault(input, url);
}

setDefaultShippingAddress = function (input) {
	var url = "/?event=user.address.setDefaultShipping";
	setAddressDefault(input, url);	
}

// For user account page.
showOrder = function (orderGUID) {
	//$('prevOrderMin_' + effect.element.id.split('_')[1]).show();
	$('prevOrderMin_' + orderGUID).hide();
	Effect.SlideDown('prevOrderFull_' + orderGUID, {duration:1});
	return;
}
// For user account page.
hideOrder = function (orderGUID) {
	Effect.SlideUp('prevOrderFull_' + orderGUID, {afterFinish:showTiny, duration:0.5});
	return;
}
// For user account page.
showTiny = function (effect) {
	$('prevOrderMin_' + effect.element.id.split('_')[1]).show();
	return;
}

// footer newsletter signup form
updateResponseDiv = function(theForm, theAction) {
	new Ajax.Request(theAction, {method: 'post', parameters: $(theForm).serialize(true),
		onSuccess: function(transport){ 
			if(transport.responseText == '"subscriptionSuccess"'){
				$('errResponse').setStyle({display:'none'});
				$('response').innerHTML = "<h4 class='stateHeader'>Thanks for Subscribing!</h4>";
				new Effect.Fade('newsletter', {duration: 0.5, queue: 'front' });
				new Effect.Appear('response', {duration: 0.5, queue: 'end' });
			}
			else if(transport.responseText == '"emailError"'){
				$('errResponse').hide().innerHTML = "Please enter a valid Email Address";
				new Effect.Appear('errResponse', {duration: 0.25});
			}
			else if(transport.responseText == '"mailinglistError"' || transport.responseText == '"subscriptionError"'){
				$('errResponse').hide().innerHTML = "We are unable to take your subscription at this time.";
				new Effect.Appear('errResponse', {duration: 0.25});
			}

		}
	});
	return false;
}

checkText = function(formField) {
	var formFieldValue = formField.value;
	var formFieldDefault = formField.title;
	if (formFieldValue == formFieldDefault) {
		$(formField).setStyle({color: '#000'}).value = "";
	}
	else if(formFieldValue == "") {
		$(formField).setStyle({color: '#CCC'}).value = formFieldDefault;
	}
}

/*
Script made by Martial Boissonneault  2001-2003 http://getElementById.com/
This script may be used and changed freely as long as this msg is intact
Visit http://getElementById.com/ for more free scripts and tutorials.
*/

timerID = null;
var active = 0;
var containers = new Hash();

function ScrollUp(area, speed){
	obj = containers.get(area);
	obj = obj.down();
	if(document.getElementById){
		if(parseInt(obj.style.left) < 0){
			obj.style.left = parseInt(obj.style.left) + speed + "px";
	}
		timerID = setTimeout("ScrollUp('" + area + "', "+speed+")", 30);
	}
}

function ScrollDown(area, speed){
	obj = containers.get(area);
	obj = obj.down();
	if(document.getElementById){
		if(parseInt(obj.style.left) > containers.get(area).offsetWidth - obj.offsetWidth){ 
			obj.style.left = parseInt(obj.style.left) - speed + "px";
	}
		timerID = setTimeout("ScrollDown('" + area + "', "+speed+")", 30);
	}
}

function ScrollStop(){
	if(document.getElementById){
		clearTimeout(timerID);
	}
}

function ScrollPageInit(area) {
	//if(document.getElementById){
		containers.set(area, $(area));
		//alert(typeof containers.get(area));
		obj = containers.get(area);
		//console.log(obj, "obj");
		if (obj) {
			obj = $(obj).down();
			//console.log(containers);
			obj.setStyle({ 'width': (obj.childElements().length * obj.down().getWidth()) + 'px' });
			//console.log(obj.getWidth());
		}
	//}
	/*if(document.addEventListener){
		for(i=0;i<document.getElementsByTagName('a').length;i++){
			document.getElementsByTagName('a')[i].style.position = "relative";
		}
	}*/
}

/*category,brand,collection pages*/
outputPagedItems = function (items, pageNum) {
	var content = "";
	if (pageNum) {
		var pageItems = items[pageNum - 1];
		//console.log(pageItems, pageNum);
		if (pageItems.size()) {
			pageItems.each(function (item) {
				if (item) {
					//content += '<div class="category_product_photo" onclick="document.location.href=\'' + item.url + '\';">';
					content += '<div class="category_product_photo"><a href="' + item.url + '">';
					content += '<img src="' + item.image + '" width="105" height="159"/>';
					//content += outputFrame();
					content += '<div class="product_photo_frame"></div>';
					content += item.label + '</a></div>';
				}
			});
		}
		//document.write(content);
	}
	return content;
}

pageTo = function (categoryGUID, i) {
	var currCategory = $('category_set_' + categoryGUID);
	var haveCategoryImage = parseInt(currCategory.readAttribute('haveCategoryImage'));
	if (!haveCategoryImage)
		haveCategoryImage = 0;

	var itemsPerPage = numVisibleItems - haveCategoryImage;
	var numItems = ci.get(categoryGUID).size();
	var itemsPaged = ci.get(categoryGUID).eachSlice(itemsPerPage);
	var numPages = itemsPaged.size();
	if (i > 0 && i <= numPages) {
		if (currCategory.readAttribute('categoryItemCount') > itemsPerPage) {
			res = currCategory.select('[i]');
			res.each(function (elem) {
									if (elem.readAttribute('i') == i)
										elem.setStyle({fontWeight:'bold', textDecoration: 'underline'});
									else
										elem.setStyle({fontWeight:'normal', textDecoration: 'none'});
								})
			currCategory.writeAttribute('currPage', i);
		}
		currCategory.down('.categoryItems').update(outputPagedItems(itemsPaged, i));
	}
} 

pagePrevious = function (categoryGUID){
	var currCategory = $('category_set_' + categoryGUID);
	var currPage = currCategory.readAttribute('currPage');
	pageTo(categoryGUID, currPage - 1);
}
pageNext = function (categoryGUID){
	var currCategory = $('category_set_' + categoryGUID);
	//console.log('category_set_' + categoryGUID, currCategory);
	var currPage = parseInt(currCategory.readAttribute('currPage'));
	pageTo(categoryGUID, currPage + 1);
}