﻿/* Site.js */

var InstockStoreId = 'TC';
var InstockUrl = 'http://www.shopbloc.com/instock/';

$.fn.reverse = [].reverse;

function EqualWidth(group, width) {
	group = $(group);
	var m = (width == null ? 0 : width);
	if (m == 0) {
		group.each(function () {
			var w = $(this).width();
			if (w > m) m = w;
		});
	}
	group.width(m);
	return m;
}

function EqualHeight(group, height) {
	group = $(group);
	var m = (height == null ? 0 : height);
	if (m == 0) {
		group.each(function () {
			var h = $(this).height();
			if (h > m) m = h;
		});
	}
	group.height(m);
	return m;
}

function GetUrlVars() {
	var vars = [], pair;
	var kvs = window.location.href.slice(window.location.href.indexOf('?') + 1).split(/[&#]+/);
	for (var i = 0; i < kvs.length; i++) {
		pair = kvs[i].split('=');
		var k = decodeURI(pair[0]), v = decodeURI(pair[1]);
		vars.push(k);
		vars[k] = v;
	}
	return vars;
}

function GetUrlVar(key, default_value) {
	var vars = GetUrlVars();
	return (key in vars) ? vars[key] : default_value;
}

function SetCookie(key, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = key + "=" + value + expires + "; path=/";
}

function GetCookie(key) {
	var cookies = document.cookie.split(';');
	var regex = new RegExp("^" + key + "=(.+)$");
	for (var i = 0; i < cookies.length; i++) {
		var cookie = $.trim(cookies[i]);
		var results = regex.exec(cookie);
		if (results != null && results.length > 1)
			return results[1];
	}
	return null;
}

function DeleteCookie(key) {
	SetCookie(key, "", -1);
}


/* User-friendly */

var uf_key = "user-friendly";
var uf_value = GetCookie(uf_key);

function SetUserFriendly() {
	if (uf_value != '1') {
		SetCookie(uf_key, '1', 0);
		uf_value = '1';
	}
}

function IsUserFriendly() {
	return (uf_value == '1');
}

if (uf_value != '1') {
	$(document).one('keydown', SetUserFriendly);
	$(document).one('mouseover', SetUserFriendly);
	$(document).one('click', SetUserFriendly);
}


/* First ready handler */

$(function () {
	// Set copyright year
	$('.copyright span.year').html((new Date()).getFullYear());
	EqualWidth($('.featured-categories .category'));
});

$(function () {
	/* Validate quantity inputs */
	$('.body.item .content .vitals .quantity input').change(function () {
		var i = $(this).val();
		if (isNaN(i)) i = 0;
		$(this).val(Math.max(0, parseInt(i)));
	});
});


/* Setup Nav */

function ShowMenu(ul) {
	if (ul.length != 1) return;

	var li = ul.parent();
	var lis = ul.children('li');

	if (lis.length == 0)
		return;

	var height = 0, width = 0;

	// reset positions
	ul.css({
		'height': '', 'width': '',
		'top': '', 'left': ''
	});
	lis.css({
		'max-width': '',
		'margin-top': '',
		'margin-left': '',
		'width': ''
	});

	// determine bounds
	var top_offset = ul.parent().height();
	var max_height = $(window).height() - top_offset - 30;
	var max_width = $('.neck').width();

	// prepare columns
	var columns = [];
	var col_len = (lis.length < 16)
		? Math.floor(max_height / (lis.first().height() + 1))
		: Math.ceil(lis.length / 4);
	for (var o = 0; o < lis.length; o += col_len)
		columns.push(lis.slice(o, o + col_len).get());

	lis.css('max-width', Math.floor(max_width / columns.length));

	// set positions
	var total_width = 0;
	for (var c = 0; c < columns.length; c++) {
		var total_height = 0;
		var rows = $(columns[c]);
		for (var r = 0; r < rows.length; r++) {
			var h = $(rows[r]).height();
			var top = r * h;
			if (top != 0)
				$(rows[r]).css('top', top);
			total_height += h;
			if (total_height > height)
				height = total_height;
		}
		rows.addClass('inline');
		var w = EqualWidth(rows);
		rows.removeClass('inline');
		if (total_width > 0)
			rows.css('left', total_width);
		var first = rows.first();
		total_width += w;
		if (total_width > width)
			width = total_width;
	}
	ul.css({
		'height': height, 'width': width,
		'top': top_offset,
		'left': Math.min(
			ul.parent().position().left,
			Math.max(
				ul.parent().position().left + ul.parent().width() - width,
				Math.floor((max_width - width) / 2)
			)
		)
	});
}

$(function () {
	$('.neck .nav ul').children('li').each(function () {
		if ($('ul', this).length > 0)
			$(this).addClass('expand');
	}).hover(
		function () { ShowMenu($(this).addClass('hover').children('ul')); },
		function () { $(this).removeClass('hover'); }
	);
	$('.neck .nav a').click(function () {
		$('.neck .nav ul li.hover').removeClass('hover');
	});
});


/* Breadcrumbs */

$(function () {
	$('.breadcrumbs span').hover(
		function () {
			$(this).addClass('hover').children('div').each(function () {
				var parent = $(this).parent();
				var pos = parent.offset();
				pos.top += parent.height() - $(window).scrollTop();
				$(this).css({ 'top': pos.top, 'left': pos.left });
			});
		},
		function () { $(this).removeClass('hover'); }
	);
});


/* Toggles */

function Toggle(containers, name) {
	if (name == undefined || name == null) name = '';
	$(containers).each(function () {
		var toggle = $('.toggle', this);
		if (toggle.length == 0) {
			toggle = $('<a class="toggle" href="#">Show ' + name + '</a>')
			$(this).append(toggle);
			toggle.click(function () {
				toggle.siblings().show();
				toggle.hide();
				return false;
			});
		}
		toggle.siblings().hide();
		toggle.show();
	});
}



/* Resize Queue */

var ResizeCallback = null;
function QueueResize() {
	if (ResizeCallback != null)
		clearTimeout(ResizeCallback);
	ResizeCallback = setTimeout('$(window).resize()', 100);
}


/* Category Contents */

$(function () {
	var categories = $('.body.category .contents .category.eqh');
	EqualHeight(categories.height('auto'));
	categories.find('img').load(function () {
		// Make all categories equal height
		EqualHeight($(this).parent().parent()
			.siblings().andSelf()
			.height('auto')
		);
	})
});


/* Pagination */

var NumProducts = 0;
var PageSize = 20;
var NumPages = 1;

function GetSort() {
	var sort = $.bbq.getState('s') || 'default';
	if (sort != 'default' && sort != 'name' && sort != 'price') sort = 'default';
	return sort;
}

function GetPage() {
	var page = $.bbq.getState('p');
	if (page == undefined || page == null) page = (IsUserFriendly() ? 1 : 0);
	page = Math.max(0, Math.min(NumPages, isNaN(page) ? 0 : parseInt(page)));
	return page;
}

function SortByDefault() { ChangePagination('default', null); return false; }
function SortByName() { ChangePagination('name', null); return false; }
function SortByPrice() { ChangePagination('price', null); return false; }
function PagePrev() { if (GetPage() > 1) ChangePagination(null, GetPage() - 1); return false; }
function PageNext() { ChangePagination(null, GetPage() + 1); return false; }
function PageSelect() { ChangePagination(null, $(this).html()); return false; }

function Paginate() {
	if (window.Paginated == true) return;
	window.Paginated = true;

	var content = $('.paginate');
	if (content != null && content.length > 0) {
		var products = content.find('.product').each(function (index) {
			$(this).data('order', index + 1);
		});

		NumProducts = products.length;
		NumPages = Math.ceil(NumProducts / PageSize);
		
		if (products.length > 0) {
			var sort = $('<div class="sort"></div>')
				.append('Sort By: ')
				.append('<a class="default" href="#">Default</a>')
				.append('<a class="name" href="#">Name</a>')
				.append('<a class="price last" href="#">Price</a>');
			var page = $('<div class="page"></div>');
			if (NumPages > 1) {
				page.append('<a class="prev" href="#">&lsaquo; Prev</a>')
					.append('&middot; <span></span> &middot;')
					.append('<a class="next" href= "#">Next &rsaquo;</a>');
			}
			var showing = $('<div class="showing"></div>');
			var pages = $('<div class="pages"></div>');
			pages.append('Page ');
			for (var p = 0; p <= NumPages; p++) {
				pages.append(
					$(document.createElement('a'))
						.attr('href', '#')
						.html((p < NumPages) ? p + 1 : 'View All')
						.attr('class', (p == NumPages) ? 'last' : '')
				);
			}
			var controls = $('<div class="controls"></div>')
				.append(
					$('<div></div>')
						.append(sort)
						.append(page)
						.append(showing)
				);
			if (NumPages > 1) {
				controls.append(
					$('<div></div>')
						.append(pages)
				);
			}
			content.prepend(controls);
			content.append(controls.clone());

			// Add handlers after controls are cloned
			$('.paginate .controls .sort .default').click(SortByDefault);
			$('.paginate .controls .sort .name').click(SortByName);
			$('.paginate .controls .sort .price').click(SortByPrice);
			$('.paginate .controls .page .prev').click(PagePrev);
			$('.paginate .controls .page .next').click(PageNext);
			$('.paginate .controls .pages a').click(PageSelect);

			UpdatePagination();
		}
	}
}

function UpdatePagination() {
	var content = $('.paginate');
	if (content != null) {
		var s = GetSort();
		var p = GetPage();

		// Detach
		var products = $('.paginate .products .product').detach();

		// Perform Sort
		if (s == 'default') {
			products.sort(function (a, b) {
				var ao = parseInt($(a).data('order'));
				var bo = parseInt($(b).data('order'));
				if (ao && bo) {
					if (ao < bo) return -1;
					if (ao > bo) return 1;
				}
				var ap = $(a).data('product');
				var bp = $(b).data('product');
				if (ap && bp) {
					if (ap.name < bp.name) return -1;
					if (ap.name > bp.name) return 1;
				}
				return 0;
			});
		}
		else if (s == 'name') {
			products.sort(function (a, b) {
				var ap = $(a).data('product');
				var bp = $(b).data('product');
				if (ap && bp) {
					if (ap.name < bp.name) return -1;
					if (ap.name > bp.name) return 1;
				}
				return 0;
			});
		}
		else if (s == 'price') {
			products.sort(function (a, b) {
				var ap = $(a).data('product');
				var bp = $(b).data('product');
				if (ap && bp) {
					if (parseFloat(ap.sale_price) < parseFloat(bp.sale_price)) return -1;
					if (parseFloat(ap.sale_price) > parseFloat(bp.sale_price)) return 1;
					if (ap.name < bp.name) return -1;
					if (ap.name > bp.name) return 1;
				}
				return 0;
			});
		}

		// Re-attach
		products.each(function () {
			$('.paginate .products').append(this);
		});

		// Update Page
		var offset = ((p > 0) ? ((p - 1) * PageSize) : 0);
		var limit = (p > 0) ? Math.min(NumProducts - offset, PageSize) : NumProducts;

		var controls = content.find('.controls');
		if (NumPages > 0) {
			var page = controls.find('.page');

			var span = page.find('span');
			var prev = page.find('.prev');
			var next = page.find('.next');

			if (p == 0) {
				span.html('Viewing all items');
				prev.hide();
				next.hide();
			}
			else {
				span.html('Page ' + p + ' of ' + NumPages);
				if (p > 1) prev.removeClass('disabled');
				else prev.addClass('disabled');
				prev.show();
				if (p < NumPages) next.removeClass('disabled');
				else next.addClass('disabled');
				next.show();
			}

			var showing = controls.find('.showing');
			showing.html('showing products ' + (offset + 1) + '-' + (offset + limit) + ' of ' + NumProducts);

			var pages = controls.find('.pages');
			pages.each(function () {
				$(this).find('a')
					.removeClass('hl')
					.eq((p > 0) ? p - 1 : NumPages)
					.addClass('hl');
			});

			controls.show();
		}
		else
			controls.hide();

		//var products = content.find('.product');
		products.addClass('hidden').data('hidden', true)
				.slice(offset, offset + limit)
				.removeClass('hidden').data('hidden', false);
	}
}

function ChangePagination(sort, page) {
	// Get current state
	var s = GetSort();
	var p = GetPage();

	// Set default param values
	sort = sort || s;
	if (page == undefined || page == null) page = p;

	// Prepare new state
	if (sort != 'default' && sort != 'name' && sort != 'price') sort = 'default';
	page = Math.max(0, Math.min(NumPages, isNaN(page) ? 0 : parseInt(page)));

	// Reset page on sort change
	if (s != sort && p > 0) page = 1;

	// Update state
	if (p != page || s != sort || $.bbq.getState('p') == undefined) {
		//var state = { 'p': page };
		//if (sort != 'default') state['s'] = sort;
		var state = { 'p': page, 's': sort };
		$.bbq.pushState(state);
	}
}

$(function () {
	if ($('.paginate').length > 0) {
		// Bind a callback that executes when document.location.hash changes.
		$(window).bind("hashchange", function () {
			$(window).scrollTop(0);
			UpdatePagination();
			setTimeout('BuildProducts()', 10);

			// Hide description
			var category_desc = $('.body.category .content .desc');
			if (category_desc.length > 0) {
				if (IsUserFriendly() && window.location.href.indexOf('#') > -1)
					Toggle(category_desc, 'text');
				else
					$('.toggle', category_desc).hide().siblings().show();
			}
		});
		$(window).trigger("hashchange");
	}
});


/* Shipping */

$(function () {
	var td = $('.vitals .shipping  td');
	if (td.length == 0)
		return;

	var ds = 0;
	var days = 0;
	var shipping_msg = td.find('.itemshippingmsg').html();
	var matches = (/ships within (\d+) (\w+)\./).exec(shipping_msg);
	if (matches != null && matches.length == 3) {
		ds = parseInt(matches[1]);
		if (matches[2] == "weeks")
			ds = ds * 7;
		td.append('<div class="alert">Standard Ground Delivery Only - No Air Delivery</div>');
	}

	return; // temporarily disabled

	if (InstockStoreId == 'IDT') {
		var now = new Date();
		if (now.getUTCMonth() == 11) { // (0-11)
			var dom = now.getUTCDate(); // day of month (1-31)
			var late = (now.getUTCHours() > 19); // (0-23), 1pm MST (UTC-7)
			if (late) dom = dom + 1;
			if (dom > 10 && dom <= 25) {

				// how many shipping days are left before Christmas?

				var day = now.getUTCDay(); // day of week (0-6)
				if (late) day = (day == 6 ? 0 : day + 1);

				var left = 0;
				for (var d = dom; d < 24; d++, day = (day == 6 ? 0 : day + 1)) {
					if (day > 0 && day < 6) {
						left++;
					}
				}

				td.append('<br style="clear: both;" />');
				if (ds == 0) td.append('<br />');
				td.append('<div><b>Will it arrive by December 24th?</b><br/><table border="0" cellpadding="0" cellspacing="0">');

				var methods = { 'Ground': [1, 6], '3 Day': [3, 4], '2 Day': [2, 3], 'Next Day': [1, 2] };

				for (var k in methods) {
					var c = 'red', s = '';
					if (k == 'Ground' || ds == 0) {
						var guaranteed = (methods[k][1] <= left);
						if (guaranteed)
							c = 'green';
						else
							s = 'Not ';
						s = s + 'Guaranteed';
						td.append('<div>' + k + ' : <span style="color:' + c + '">' + s + '</span></div>');
					}
				}

				td.append('</table></div>');
			}
		}
	}
});


/* Headlines */

var HeadlineDuration = 5000;
var HeadlineSpeed = 500;
function CycleHeadlines() {
	var headlines = $('.neck .headlines');
	var divs = headlines.children('div');
	if (divs.length > 0) {
		if (divs.length > 1)
			setTimeout('CycleHeadlines()', HeadlineDuration + HeadlineSpeed);
		var next = divs.eq(0).detach();
		divs.fadeOut(HeadlineSpeed);
		headlines.append(next);
		next.fadeIn(HeadlineSpeed * 2);
	}
}
$(CycleHeadlines);


/* Rotating Banners */

var BannerDuration = 5000;
var BannerSpeed = 500;
var BannerIndex = 0;
var BannerCallback = null;

function CycleBanners() {
	var container = $('.rotating-banners');
	var banners = $('.banners div', container);
	if (banners.length > 1) {
		BannerCallback = setTimeout('CycleBanners()', BannerDuration + BannerSpeed);
		if (++BannerIndex >= banners.length) BannerIndex = 0;
		banners.eq(BannerIndex).fadeIn(BannerSpeed).siblings().fadeOut(BannerSpeed);
		$('.controls a', container)
			.eq(BannerIndex).addClass('active')
			.siblings().removeClass('active');
	}
}

$(function () {
	var container = $('.rotating-banners');
	var banners = $('.banners div', container);
	if (banners.length > 1) {
		// setup controls
		var controls = $('.controls', container);
		for (var i = 0; i < banners.length; i++) {
			var control = $('<a href="#"></a>');
			controls.append(control);
			control.click(function () {
				if (BannerCallback != null) {
					clearTimeout(BannerCallback);
					BannerCallback = null;
				}
				BannerIndex = $(this).index() - 1;
				CycleBanners();
				return false;
			});
			if (i == 0) control.addClass('active');
		}

		// Start cycling
		BannerCallback = setTimeout('CycleBanners()', BannerDuration + BannerSpeed);
	}
});


/* Recently Viewed */

var RecentlyViewedCookie = "recently-viewed";
var RecentlyViewedAgeInDays = 7;
var RecentlyViewedItemMax = 3;
var RecentlyViewed = JSON.parse(GetCookie(RecentlyViewedCookie));

function AddRecentlyViewed(data) {
	if (data != null) {
		if (RecentlyViewed == null)
			RecentlyViewed = [];
		for (var i = 0; i < RecentlyViewed.length; i++) {
			if (RecentlyViewed[i].id == data.id) {
				RecentlyViewed.splice(i, 1);
				break;
			}
		}
		RecentlyViewed.push(data);
		while (RecentlyViewed.length > RecentlyViewedItemMax)
			RecentlyViewed.shift();
		SetCookie(RecentlyViewedCookie, JSON.stringify(RecentlyViewed), RecentlyViewedAgeInDays);
	}
}

$(function () {
	if (RecentlyViewed != null) {
		var div = $('.recently-viewed');
		for (var i = 0; i < RecentlyViewed.length; i++) {
			var p = RecentlyViewed[i];
			div.append(
				$('<div class="product eqh ' + p.id + '"></div>').append(
					'<a href="' + p.id + '.html">' + p.name + '</a>'
				)
			);
		}
		div.show();
		LoadProducts(RecentlyViewed);
	}
});


/* In Stock */

function ItemInStock() {
	var code = $('.vitals .item-number td').html();
	if (code != null) {
		$.ajax({
			url: InstockUrl,
			data: {
				't': '1',
				'sid': InstockStoreId,
				'skus': code
			},
			dataType: 'jsonp',
			success: function (data) {
				if ('outofstocks' in data) {
					var outofstocks = data['outofstocks'];
					$('.content .vitals tr.quantity').after(
						$('<tr class="in-stock"></tr>')
							.append('<th>Out of Stock</th>')
							.append('<td><span class="no">' +
								outofstocks.join(', ') +
								'</span></td>')
					);
					$('.content .vitals tr.color select')
					.add('.content .vitals tr.size select')
					.add('.content .vitals tr.style select')
					.each(function () {
						var options = $('option', this);
						var select = true;
						options.each(function () {
							var option = $(this);
							if (outofstocks.indexOf(option.html()) > -1) {
								option.attr('disabled', 'disabled');
							}
							else if (select) {
								option.attr('selected', 'selected');
								select = false;
							}
						});
						if (select && options.length > 0) {
							var option = $('<option>--</option>');
							$(this).prepend(option);
							option.attr('selected', 'selected');
						}
					});
				}
				else if ('instock' in data) {
					var instock = (data['instock'] === 1);
					$('.content .vitals tr.quantity').after(
						$('<tr class="in-stock"></tr">')
							.append('<th>In Stock</th>')
							.append('<td><span class="' + (instock ? 'yes' : 'no') + '">' +
								(instock ? 'Yes' : 'No') +
								'</span></td>')
					);
				}
				QueueResize();
			}
		});
	}
}
$(ItemInStock);

function ProductsInStock(products) {
	if (window.Instocks == undefined)
		window.Instocks = [];
	var codes = $(products).map(function (index, element) {
		var p = $(element).data('product');
		if (p == null || p.code == null || (p.code in window.Instocks))
			return null;
		else {
			// Once per unique id
			window.Instocks[p.code] = p;
			return p.code;
		}
	}).get();
	if (window.InstockQueue == undefined)
		window.InstockQueue = [];
	for (var i = 0; i < codes.length; i++)
		window.InstockQueue.push(codes[i]);
	setTimeout('ProcessInstocks()', 10);
};

function ProcessInstocks() {
	var queue = window.InstockQueue;
	if (queue != undefined && queue.length > 0) {
		var len = Math.min(queue.length, PageSize);
		window.InstockQueue = queue.slice(len);
		var codes = queue.slice(0, len);
		if (codes.length > 0) {
			var numProducts = codes.length;
			var numPages = Math.ceil(numProducts / PageSize);
			for (var p = 0; p < numPages; p++) {
				var offset = p * PageSize;
				var limit = Math.min(numProducts - offset, PageSize);
				var skus = codes.slice(offset, offset + limit);
				$.ajax({
					url: InstockUrl,
					data: { 't': '0', 'sid': InstockStoreId, 'skus': skus.join('|') },
					dataType: 'jsonp',
					success: function (data) {
						var products = $('.product');
						for (var id in data) {
							var instock = (data[id] === 1);
							products.filter(function (index) {
								var p = $(this).data('product');
								return (p != null && p.code != null && p.code == id);
							}).each(function () {
								$('.sale-price', this).after(
									$('<div class="in-stock" style="display:none;">In Stock: </div>')
										.append(
											'<span class="' + (instock ? 'yes' : 'no') + '">' +
											(instock ? 'Yes' : 'No') +
											'</span>'
										).fadeIn('fast')
								);
							});
						}
						QueueResize();
					}
				});
			}
			if (window.InstockQueue.length > 0)
				setTimeout('ProcessInstocks()', 10);
		}
	}
}


/* Adjust mis-aligned elements */

$(window).resize(function () {
	// Center product share links
	$('.product-share-links').each(function () {
		var container = $(this).css('margin-left', '0');
		var li = $('li', container);
		var wt = container.width();
		var w = li.first().width();
		if (w > 0) {
			var m = (wt - (Math.min(Math.floor(wt / w), li.length) * w)) / 2;
			container.css('margin-left', m + 'px');
		}
	});
	// Set uniform heights
	$('.body.item .content').css('height', '');
	EqualHeight($('.body.item .content').add('.body.item .related'));
	$('.body.item .related').css('height', '');
	// Adjust item vitals width
	$('.body.item .content').each(function () {
		var w = $(this).width() - $('.image', this).width() - 30;
		$('.vitals', this).width(w);
	});
});


/* Zoom */

var ZoomSpeed = 200;
var ZoomImages = [];
var ZoomAnimations = {};
var LastZoomIndex = -1;

function InitZoom(data) {
	if (data.length > 0 && $('#ImageZoom').length == 0) {
		// Prepare the zoom overlay
		var ImageZoom = $('<form id="ImageZoom"></form>');
		var backdrop = $('<div class="backdrop"></div>');
		var bounds = $('<div class="bounds"></div>');
		var close_button = $('<a href="#" class="close">Close [x]</a>');
		var full = $('<div class="full"></div>');
		var thumbs = $('<div class="thumbs"></div>');

		// Prepare images
		for (var i = 0; i < data.length; i++) {
			var thumb_src = data[i]['thumb'];
			var full_src = data[i]['full'];
			if (thumb_src && full_src) {
				var thumb_image = new Image;
				var full_image = new Image;
				$(thumb_image).load(function () {
					$(this).data({
						'height': this.height,
						'width': this.width,
						'ready': true
					});
				});
				$(full_image).load(function () {
					$(this).click(function () {
						ZoomToggle(false);
					});
					$(this).data({
						'height': this.height,
						'width': this.width,
						'ready': true
					});
				});
				thumb_image.src = thumb_src;
				full_image.src = full_src;
				ZoomImages.push(full_image);
				thumbs.append(thumb_image);
			}
		}

		// Add ImageZoom to DOM
		$('body').append(
			ImageZoom
				.append(backdrop)
				.append(bounds
					.append(full)
					.append(thumbs)
					.append(close_button)
				)
		);

		if (ZoomImages.length > 1) // Add thumbnails to item page
			$('.body.item .content .image .full').after(thumbs.clone());

		// Create handlers
		$(document).keydown(function (e) {
			if ($('#ImageZoom').is(':visible')) {
				switch (e.which) {
					case 8: // Backspace
					case 27: // Esc
					case 32: // Space
					case 88: // X
						ZoomToggle(false);
						e.preventDefault();
						break;
				}
			}
		});
		/*
		$(window).scroll(function (e) {
		if ($('#ImageZoom').is(':visible')) {
		e.preventDefault();
		}
		});
		*/
		$('#ImageZoom .thumbs img').each(function (index, element) {
			$(this).click(function () {
				Zoom(index);
				return false;
			});
		});
		$('#ImageZoom .close').click(function () {
			ZoomToggle(false);
			return false;
		});
		$('.body.item .content .image .full').add('.body.item .content .image .zoom')
			.click(function () {
				Zoom(0);
				return false;
			});
		$('.body.item .content .image .thumbs img').each(function (index, element) {
			$(this).click(function () {
				Zoom(index);
				return false;
			});
		});

		$(window).resize(ZoomResize);
	}
}

function SetAnimations(name, element, event_key, fx, duration, pre_callback, post_callback) {
	element = $(element).get();
	if (element == null) return;
	duration = (duration == null) ? 0 : duration;
	var obj = $(element).data(event_key + '_fx', fx);
	// Remove existing handlers
	obj.unbind(event_key);
	// Add new handler
	obj.bind(event_key, function () {
		if (fx == null) return;
		if (pre_callback != null) obj.each(pre_callback);
		if (!isNaN(duration) && duration <= 0) {
			obj.css(fx);
			if (post_callback != null) obj.each(post_callback);
		}
		else {
			var options = { 'duration': duration, 'queue': false, 'easing': 'swing' };
			if (post_callback != null)
				options['complete'] = function () { $(this).each(post_callback); };
			obj.animate(fx, options);
		}
	});
	// Store list of objects with animations
	ZoomAnimations[name] = element;
}

function SnapAnimation(name, event_key) {
	if (!(name in ZoomAnimations)) return;
	var element = ZoomAnimations[name];
	element = $(element).get();
	if (element == null) return;
	$(element).each(function () {
		var obj = $(this);
		var fx = obj.data(event_key + '_fx');
		if (fx == null) return;
		obj.css(fx);
	});
}

function Show() { $(this).show(); }
function Hide() { $(this).hide(); }

function ZoomResize() {
	var ImageZoom = $('#ImageZoom');
	var bounds = $('.bounds', ImageZoom);
	var full = $('.full', ImageZoom);
	var full_img = $('img', full);
	var thumbs = $('.thumbs', ImageZoom);
	var thumbs_imgs = $('img', thumbs);
	var close_button = $('.close', ImageZoom);

	var window_height = $(window).height();
	var window_width = $(window).width();
	var y = window_height / 2;
	var x = window_width / 2;

	var isVisible = ImageZoom.is(":visible");

	// Set default positions
	ImageZoom.show();
	thumbs.css({
		'max-width': $('#container').width(),
		'height': 'auto', 'width': 'auto'
	});
	full.css({
		'max-width': $('#container').width(),
		'height': 'auto', 'width': 'auto'
	});

	// ImageZoom
	ImageZoom.each(function () {
		var obj = $(this);
		var name = 'ImageZoom';

		obj.css({
			'top': 0, 'bottom': 0,
			'right': 0, 'left': 0
		});

		SetAnimations(name, this, 'open', {
			'top': 0, 'bottom': 0,
			'right': 0, 'left': 0
		}, ZoomSpeed, Show);

		SetAnimations(name, this, 'close', {
			'top': Math.floor(y), 'bottom': Math.ceil(y),
			'right': Math.ceil(x), 'left': Math.floor(x)
		}, ZoomSpeed, null, Hide);

		SnapAnimation(name, 'open');
	});

	// bounds
	bounds.each(function () {
		var obj = $(this);
		var name = 'bounds';

		obj.css({
			'top': 0, 'bottom': 0,
			'right': 0, 'left': 0
		});

		var min_height = obj.css('min-height');
		var min_width = obj.css('min-width');

		SetAnimations(name, this, 'open', {
			'min-height': min_height,
			'min-width': min_width,
			'top': 0, 'bottom': 0,
			'right': 0, 'left': 0
		}, ZoomSpeed);

		SetAnimations(name, this, 'close', {
			'min-height': 0,
			'min-width': 0,
			'top': 0, 'bottom': 0,
			'right': 0, 'left': 0
		}, ZoomSpeed);

		SnapAnimation(name, 'open');
	});

	if (thumbs_imgs.length > 1) {
		// thumbs_imgs
		thumbs_imgs.each(function (index) {
			var obj = $(this).css({ 'height': 'auto', 'width': 'auto' });
			var name = 'thumb' + index;
			var h = obj.height(), w = obj.width();
			SetAnimations(name, this, 'open', { 'height': h, 'width': w }, ZoomSpeed);
			SetAnimations(name, this, 'close', { 'height': 0, 'width': 0 }, ZoomSpeed);
			SnapAnimation(name, 'open');
		});

		// thumbs
		thumbs.each(function () {
			var obj = $(this).css({ 'height': 'auto', 'width': 'auto' });
			var name = 'thumbs';
			var h = obj.height(), w = obj.width();
			SetAnimations(name, this, 'open', {
				'height': h, 'width': w,
				'margin-top': -Math.ceil(h / 2)
			}, ZoomSpeed);
			SetAnimations(name, this, 'close', {
				'height': 0, 'width': 0,
				'margin-top': 0
			}, ZoomSpeed);
			SnapAnimation(name, 'open');
		});
	}
	else {
		thumbs_imgs.hide();
		thumbs.hide();
	}

	// full
	full.each(function () {
		var obj = $(this);
		var name = 'full';
		SetAnimations(name, this, 'open', { 'right': thumbs.width() }, ZoomSpeed);
		SetAnimations(name, this, 'close', { 'right': 0 }, ZoomSpeed);
		SnapAnimation(name, 'open');
	});

	// full_img
	full_img.each(function () {
		var obj = $(this);
		var name = 'full_img';

		var max_height = Math.max(0, full.height() - 20);
		var max_width = Math.max(0, full.width() - 20);

		obj.css({
			'max-height': max_height,
			'max-width': max_width,
			'height': 'auto', 'width': 'auto'
		});

		var h = obj.height(), w = obj.width();
		if (h < max_height && w < max_width) {
			var mh = Math.min(h * 2, max_height) / h;
			var mw = Math.min(w * 2, max_width) / w;
			h *= Math.min(mh, mw);
			w *= Math.min(mh, mw);
		}

		SetAnimations(name, this, 'open', {
			'height': h, 'width': w,
			'margin-top': -Math.ceil(h / 2),
			'margin-left': -Math.ceil(w / 2)
		}, ZoomSpeed);

		SetAnimations(name, this, 'close', {
			'height': 0, 'width': 0,
			'margin-top': 0,
			'margin-left': 0
		}, ZoomSpeed);

		SnapAnimation(name, 'open');
	});

	// close_button
	close_button.each(function () {
		var obj = $(this).css({ 'height': 'auto', 'width': 'auto' });
		var name = 'close_button';
		var h = obj.height(), w = obj.width();
		SetAnimations(name, this, 'open', { 'height': h, 'width': w }, ZoomSpeed);
		SetAnimations(name, this, 'close', { 'height': 0, 'width': 0 }, ZoomSpeed);
		SnapAnimation(name, 'open');
	});

	if (!isVisible) {
		SnapAnimation('close_button', 'close');
		thumbs_imgs.each(function (i) { SnapAnimation('thumb' + i, 'close'); });
		SnapAnimation('thumbs', 'close');
		SnapAnimation('full_img', 'close');
		SnapAnimation('full', 'close');
		SnapAnimation('bounds', 'close');
		SnapAnimation('ImageZoom', 'close');
		ImageZoom.hide();
	}
}

function Zoom(index) {
	if (ZoomImages.length > 0) {
		var i = Math.max(0, Math.min(ZoomImages.length - 1, (index == null) ? 0 : parseInt(index)));
		var image = ZoomImages[i];
		if (image != null) {
			var ready = $(image).data('ready');
			if (ready === true) { /* display image */
				if (LastZoomIndex != index) {
					LastZoomIndex = index;
					$('#ImageZoom .full img').detach(); // detach prev
					$('#ImageZoom .full').append(image); // attach new
				}
				ZoomToggle(true);
			}
			else if (ready === false) { /* do nothing */ }
			else if (ready === null) { /* add a load handler */
				$(image).data('ready', false).load(function () { Zoom(i); });
			}
		}
	}
}

function ZoomToggle(show) {
	ZoomResize();
	var isVisible = $('#ImageZoom').is(':visible');
	for (var k in ZoomAnimations) {
		var element = $(ZoomAnimations[k]).get();
		if (element == null) continue;
		if (show) {
			if (isVisible) { SnapAnimation(element, 'open'); }
			else {
				SnapAnimation(element, 'close');
				$(element).trigger('open');
			}
		}
		else {
			if (isVisible) {
				SnapAnimation(element, 'open');
				$(element).trigger('close');
			}
			else { SnapAnimation(element, 'close'); }
		}
	}
}


/* PopUp */

function PopUp(url, w, h) {
	var win = null;
	try {
		win = window.open(url, '_blank', 'location=0,menubar=0,status=0,toolbar=0'
			+ ',height=' + h + ',top=' + Math.floor(Math.max(0, $(window).height() - h) / 2)
			+ ',width=' + w + ',left=' + Math.floor(Math.max(0, $(window).width() - w) / 2)
		);
	}
	finally {
		return (win == null);
	}
}


/* Not Implemented */

$('.not-implemented').append('Not Implemented');


/* Accessories - Hide Variations column when none of the accessories have variations */

$(function () {
	var hasOptions = false;
	$('.body.item .content .vitals .accessories .accessory td.options').each(function () {
		if ($(this).html().length > 0)
			hasOptions = true;
	});
	if (!hasOptions)
		$('.body.item .content .vitals .accessories th.options').html('');
});


/* Site Map */

$(function () {
	$('.body.sitemap .content .directory').each(function () {
		var directory = $(this);
		directory.children('ul').find('li').each(function () {
			var li = $(this);
			var ul = li.children('ul');
			if (ul.length == 1) {
				ul.before('<span class="collapse-list">[&ndash;]</span>')
				  .before('<span class="expand-list" style="display: none;">[+]</span>');
			}
		});
		var expanders = directory.find('.expand-list').click(function () {
			$(this).siblings('ul').children('li').show();
			$(this).hide().siblings('.collapse-list').show();
		});
		var collapsers = directory.find('.collapse-list').click(function () {
			$(this).siblings('ul').children('li').hide();
			$(this).hide().siblings('.expand-list').show();
		});
		var controls = $('<div class="controls"></div>')
			.append('<a class="expand" href="#">expand all</a>')
			.append(' / ')
			.append('<a class="collapse" href="#">collapse all</a>');
		directory.prepend(controls);
		$('.expand', controls).click(function () {
			expanders.click();
			return false;
		});
		$('.collapse', controls).click(function () {
			collapsers.click();
			return false;
		});
	});
	if (GetUrlVar('x', '') == '1') {
		$('.body.sitemap .content .directory li').each(function () {
			if ($(this).children('ul').length == 0) {
				var html = $(this).html();
				var x = html.indexOf('<!--// ');
				if (x > -1) {
					x += 7;
					var y = html.indexOf(' //-->');
					if (y > x) {
						var count = parseInt(html.substring(x, y));
						$(this).children().first().append(' (' + count + ')');
					}
				}
			}
		});
	}
	if (IsUserFriendly()) $('.sitemap .directory .controls .collapse').click();
});


/* Default input values */

$(function () {
	$('input.default').each(function () {
		var def = this.defaultValue;
		if (def == undefined || def == '')
			def = this.value;
		$(this).val(def);
		$(this).focus(function () {
			if (this.value == def) {
				this.value = '';
				$(this).removeClass('default');
			}
		});
		$(this).blur(function () {
			if (this.value == '') {
				this.value = def;
				$(this).addClass('default');
			}
		});
	});
});


/* Resize events */

$(window).resize(function () {
	$('.product.eqw').parent().each(function () {
		// Make all image containers equal width
		var eqw = $(this).children('.eqw')
		EqualWidth(eqw.children('a').children('img').parent().width('auto'));
		EqualWidth(eqw.width('auto'));
	});
	$('.product.eqh').parent().each(function () {
		// Make all image containers equal height
		var eqh = $(this).children('.eqh');
		EqualHeight(eqh.children('a').children('img').parent().height('auto'));
		EqualHeight(eqh.height('auto'));
	});
});


/* Products */

function LoadProducts(data, view_button, share_buttons) {
	if (data != null && data.length > 0) {
		if (view_button != null) {
			for (var i = 0; i < data.length; i++)
				data[i].view_button = view_button;
		}
		if (share_buttons != null) {
			for (var i = 0; i < data.length; i++)
				data[i].share_buttons = share_buttons;
		}
		window.ProductData = data;
		Paginate();
		setTimeout('BuildProducts()', 10);
	}
}

function BuildProducts() {
	var data = window.ProductData;
	if (data != null) {
		var domain = window.location.href.split('/')[2];
		var products = [];
		for (var i = 0; i < data.length; i++) {
			var p = data[i];
			if (p.loaded != true) {
				$('.product.' + p.id).each(function () {
					var product = $(this);
					if (product.data('hidden') != true && product.children('a').length == 1) {
						var name = $('a', this);
						if (p.img != null) {
							product.prepend(
								$('<a class="img" href="' + p.id + '.html" title="' + p.name + '"></a>').append(
									$('<img src="' + p.img + '" alt="' + p.name + '" />').load(QueueResize)
								)
							);
						}
						//if (p.list_price != null)
						//	name.after('<div class="list-price">List Price: $' + p.list_price + '</div>');
						if (p.sale_price != null)
							product.append('<div class="sale-price">Sale Price: $' + p.sale_price + '</div>');
						if (p.colors === '1' || p.sizes === '1') {
							var div = $('<div class="more-options"></div>');
							if (p.colors === '1')
								div.append('<div class="more-colors" title="More colors available"></div>');
							if (p.sizes === '1')
								div.append('<div class="more-sizes" title="More sizes available"></div>');
							product.append(div);
						}
						if (p.share_buttons == true) {
							var url = 'http://' + domain + '/' + p.id + '.html';
							var container = $('<div class="share-buttons"></div>');
							// Facebook
							container.append(
								'<div class="fb-like">' +
									'<iframe src="//www.facebook.com/plugins/like.php?' +
										'layout=button_count&href=' + escape(url) +
									'" scrolling="no" frameborder="0"></iframe>' +
								'</div>'
							);
							// Google+
							container.append(
								'<div class="gplus-one">' +
									'<g:plusone size="medium" href="' + url + '"></g:plusone>' +
								'</div>'
							);
							product.append(container);
						}
						if (p.view_button != null) {
							product.append(
								$('<a class="view-item" href="' + p.id + '.html"></a>').append(
									$('<img src="' + p.view_button + '" alt="View Item" />')
								)
							);
						}
						products.push(product.data('product', p));
						p.loaded = true;
					}
				});
			}
			data[i] = p;
		}
		window.ProductData = data;
		if (products.length > 0) {
			// Load instocks
			ProductsInStock(products);
			// Google+ Post-op
			var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
			po.src = 'https://apis.google.com/js/plusone.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
			// Resize window
			$(window).resize();
		}
	}
}


/* Checkout */

$(function () {
	var keep_shopping = $('#ys_cartPage .ys_pageActions .ys_first a');
	if (keep_shopping.length == 1) {
		var cont = keep_shopping.clone().addClass('continue').html('Continue Shopping');
		$('#ys_pageMessage .progress').prepend('<hr />').prepend(cont);
	}
});

