if (typeof jQuery.keys !== 'function'){
	jQuery.extend({
		"keys": function(obj){
			var a = [];
			$.each(obj, function(k){ a.push(k) });
			return a;
		}
	});
}
if (typeof jQuery.exists !== 'function'){
	jQuery.extend({
		"exists": function(obj){
			var length;
			if ((typeof obj==='object')&&(obj instanceof jQuery)) {
				length = obj.length;
			}
			else {
				length = jQuery(obj).length;
			}
			return (length>0);
		}
	});
}

function bed_set_aggregator(key, row_index) {
	var $					= jQuery;
	var __this__			= this;

	this.row_index			= row_index;
	this.category_type;
	this.bed_type			= key;												// temporary value until it can be resolved..
	this.bed_id;
	this.bed_title;
	this.bed_description;
	this.default_size		= '';
	this.bed_sizes;
	this.empty_option_value	= '__range__';
	this.price_range		= '';
	this.thumbnail_class	= '$thumbList$';

	this.uses_updated_pricing_methodology;

	$(document).ready(function(){
		__this__.uses_updated_pricing_methodology	= ( $('.listItem .listItemPrices .nonsale_price').length > 0 );

		var test_for_safety = function(){
			var safe_to_begin						= false;
			if (__this__.uses_updated_pricing_methodology){
				var unpriced_items					= $('.listItem:not([prices_displayed])');
				if (unpriced_items.length === 0){
					safe_to_begin					= true;
				}
			}
			else {
				safe_to_begin						= true;
			}
			return safe_to_begin;
		};
		var poll_for_safety = setInterval(
			function(){
				var safe_to_begin = test_for_safety();
				if (safe_to_begin){
					clearInterval(poll_for_safety);
					__this__.begin();
				}
			},
			1000
		);
	});

	this.begin = function(){
		__this__.set_bed_id(__this__.bed_type);
		if (typeof __this__.bed_id          === 'undefined')	{return;}

		__this__.set_descriptive_data();
		if (typeof __this__.bed_description === 'undefined')	{__this__.bed_description = '';}
		if (typeof __this__.bed_title       === 'undefined')	{__this__.bed_title       = '';}

		__this__.remove_components_from_DOM();
		__this__.add_bed_widget_to_DOM();
	};

	this.remove_components_from_DOM = function() {
		var price_min;
		var price_max;

		$.each(this.bed_id, function(key, oBed){
			$('#' + oBed.id).closest('tr').hide();

			var price;
			if (__this__.uses_updated_pricing_methodology){
				price = $('#' + oBed.id + ' .listItemPrices .sale_price');
			}
			else {
				price = $('#' + oBed.id + ' .listItemPrices .itemPrice > span');
			}

			if (price.length === 1) {
				price = price.text().replace(/[^0-9.]/g, '');
				if (price.length >=1) {
					oBed.price = price;

					price = parseFloat(price);
					if (typeof price_min === 'undefined' || price < price_min) {price_min = price;}
					if (typeof price_max === 'undefined' || price > price_max) {price_max = price;}
				}
			}
			if (typeof oBed.price === 'undefined') {
				delete __this__.bed_id[key];
			}
			else {
				__this__.bed_id[key].price = oBed.price;
			}
		});
		this.bed_sizes = $.keys(this.bed_id);
		this.price_range = (typeof price_min === 'undefined')? '' : '$' + price_min + ' - $' + price_max;
	}

	this.add_bed_widget_to_DOM = function() {
		$.get('/site/shes_got_the_look/ajax/combined_bed_sets.html', function(html){
			var container = $('#' + __this__.bed_id.twin.id).closest('tbody');
			if (!$.exists(container)) {
				container = $('#' + __this__.bed_id.twin.id).closest('table');
			}
			container.find('script').remove();

			__this__.set_thumbnail_class(container);

			var url_flash = 'http://s7d5.scene7.com/s7/zoom/flasht_zoom.jsp?company=SerenaandLily&sku=' + __this__.bed_id.twin.id + '&config=SerenaandLily/popupMultipleViews&locale=en';
			var url_image = 'http://s7d5.scene7.com/is/image/SerenaandLily/' + __this__.bed_id.twin.id + '?' + __this__.thumbnail_class;

			var new_dropdown = $('<select></select>');
			var new_option = '<option value="' + __this__.empty_option_value + '">- Select -</option>';
			new_dropdown.append(new_option);
			$.each(__this__.bed_id, function(key, oBed){
				new_option = '<option value="' + key + '">' + oBed.description + '</option>';
				new_dropdown.append(new_option);
			});
			new_dropdown.addClass('inputreq');
			new_dropdown.change(__this__.update_bed_pricing);

			var new_title = $('<a class="scene7Popup listItemZoom" target="_blank"></a>');
			new_title.attr('href', url_flash);
			new_title.text(__this__.bed_title);

			var new_description = $('<div>' + __this__.bed_description + '</div>');		// prevent creating an array of HTMLElement
			if (typeof initialize_hover_containers === 'function') {
				initialize_hover_containers(new_description);
			}

			var new_row = $(html);												// <tr valign="top" height="85">...</tr>
			new_row = new_row.filter('tr:first');
			new_row.find('div.listItemImage a.scene7Popup'           ).each(function(){ $(this).attr('href', url_flash); });
			new_row.find('div.listItemImage a.scene7Popup:first img' ).each(function(){ $(this).attr('src',  url_image); });
			new_row.find('table#sizing_options span.select_container').append(new_dropdown);
			new_row.find('.listItemTitle > h3'                       ).append(new_title);
			new_row.find('.listItemTitle .listItemDescription'       ).append(new_description);
			new_row.find('.listItemButtons table.buttonTable .buttons a.slAddToCart > img'        ).click(__this__.add_bed_to_cart);
			new_row.find('.listItemButtons table.buttonTable                          img.addToMR').click(__this__.add_bed_to_registry);

			$('.scene7Popup', new_row).click(function(event){
				event.preventDefault();
				var lsURL = $(this).attr('href');
				var laSKUFull = lsURL.split("&");
				var laSKU = laSKUFull[1].replace(/sku=/,"").split("_");
				var lsSKU = "sku=" + laSKU[0];
				laSKUFull[1] = lsSKU;
				lsURL = laSKUFull.join("&");
				window.open(lsURL,'_blank','width=540,height=650');
			});

			__this__.inject_nth_child(container, new_row, __this__.row_index);

			if (__this__.uses_updated_pricing_methodology){
				new_row.find('.listItemPrices').show();
			}

			if ($.inArray(__this__.default_size, __this__.bed_sizes) >= 0) { __this__.default_size = __this__.empty_option_value; }
			new_dropdown.find('option[value=' + __this__.default_size + ']').attr('selected', 'selected');
			new_dropdown.change();
		});
	}

	// ============================================================================================
	// ===== helper function =====

	this.get_parent_object = function(parent) {
		if ( (typeof parent === 'object') && (parent instanceof jQuery) ) {
			return parent;
		}
		else {
			return $(parent);
		}
	};

	this.set_thumbnail_class = function(parent) {
		var __parent;
		var children;
		var child_count;

		__parent = __this__.get_parent_object(parent);
		if (__parent.length === 1) {
			children    = __parent.children();
			child_count = children.length;
			if (child_count > 0) {
				var another_image = $('.listItemImage img', children[0]);
				var regex_pattern = new RegExp('^.*?s7d5.scene7.com/is/image/SerenaandLily/.*?\\?(\\$.*?\\$)$', 'gi');
				if (regex_pattern.test(another_image.attr('src'))) {
					__this__.thumbnail_class = another_image.attr('src').replace(regex_pattern, '$1');
				}
			}
		}
	};

	this.inject_nth_child = function(parent, child, index) {
		var __parent;
		var children;
		var child_count;
		var bucket = [];

		__parent = __this__.get_parent_object(parent);
		if (__parent.length === 1) {
			children    = __parent.children();
			child_count = children.length;

			if ( (typeof index === 'undefined') || (index === 'first') || (index === 0) ) {		// default
				__parent.prepend(child);
			}
			else if ( (index === 'last') || (index >= child_count) ) {
				__parent.append(child);
			}
			else {
				$.each(children, function(i){
					if (i >= index) {
						var child = $(children[i]);
						child.detach();
						bucket.push(child);
					}
				});
				__parent.append(child);
				$.each(bucket, function(i, child){
					__parent.append(child);
				});
			}
		}
	}

	// ============================================================================================
	// ===== event handlers =====

	this.update_bed_pricing = function() {
		var chosen_size = $('#bed_widget select').find('option[selected]').attr('value');
		if ($.inArray(chosen_size, __this__.bed_sizes) >= 0) {
			var oBed = __this__.bed_id[chosen_size];
			var pricing = '$' + oBed.price;
			$('#bed_widget .listItemPrices .itemPrice > span').text(pricing);
		}
		else if (chosen_size === __this__.empty_option_value) {
			$('#bed_widget .listItemPrices .itemPrice > span').text(__this__.price_range);
		}
	}

	this.add_bed_to_cart = function(event) {
		event.preventDefault();
		var chosen_size = $('#bed_widget select').find('option[selected]').attr('value');
		if ($.inArray(chosen_size, __this__.bed_sizes) >= 0) {
			var oBed = __this__.bed_id[chosen_size];
			var chosen_qty = $('#bed_widget input:text').attr('value');

			$('#' + oBed.id + ' .listItemDetails table.listItemOptions .addtoCartQuantity input[name=qty]').attr('value', chosen_qty);
			$('#' + oBed.id + ' .listItemButtons table.buttonTable     .buttons a.slAddToCart > img').click();
		}
		else if (chosen_size === __this__.empty_option_value) {
			alert('Please select a size before adding this item to your cart.');
		}
	}

	this.add_bed_to_registry = function(event) {
		event.preventDefault();
		var chosen_size = $('#bed_widget select').find('option[selected]').attr('value');
		if ($.inArray(chosen_size, __this__.bed_sizes) >= 0) {
			var oBed = __this__.bed_id[chosen_size];
			var chosen_qty = $('#bed_widget input:text').attr('value');

			$('#' + oBed.id + ' .listItemDetails table.listItemOptions .addtoCartQuantity input#qty').attr('value', chosen_qty);
			$('#' + oBed.id + ' .listItemButtons table.buttonTable     img.addToMR').click();
		}
		else if (chosen_size === __this__.empty_option_value) {
			alert('Please select a size before adding this item to your gift registry.');
		}
	}

	// ============================================================================================
	// ===== where else could this go? =====

	this.set_bed_id = function(key) {
		var the_look_key_mapping = {
			"serene":	"aqua",
			"crisp":	"grass",
			"zen":		"bark",
			"eclectic":	"bark",
			"bold":		"grass",
			"earthy":	"bark"
		};

		var data_sets = {
			"aqua":		{
				"twin":		{"id":"BSET01-T", "description":"Twin"},
				"full":		{"id":"BSET01-F", "description":"Full"},
				"queen":	{"id":"BSET01-Q", "description":"Queen"},
				"king":		{"id":"BSET01-K", "description":"King"},
				"CA_king":	{"id":"BSET01-C", "description":"California King"}
			},
			"bark":		{
				"twin":		{"id":"BSET02-T", "description":"Twin"},
				"full":		{"id":"BSET02-F", "description":"Full"},
				"queen":	{"id":"BSET02-Q", "description":"Queen"},
				"king":		{"id":"BSET02-K", "description":"King"},
				"CA_king":	{"id":"BSET02-C", "description":"California King"}
			},
			"grass":	{
				"twin":		{"id":"BSET03-T", "description":"Twin"},
				"full":		{"id":"BSET03-F", "description":"Full"},
				"queen":	{"id":"BSET03-Q", "description":"Queen"},
				"king":		{"id":"BSET03-K", "description":"King"},
				"CA_king":	{"id":"BSET03-C", "description":"California King"}
			},
			"navy":	{
				"twin":		{"id":"BSET04-T", "description":"Twin"},
				"full":		{"id":"BSET04-F", "description":"Full"},
				"queen":	{"id":"BSET04-Q", "description":"Queen"},
				"king":		{"id":"BSET04-K", "description":"King"},
				"CA_king":	{"id":"BSET04-C", "description":"California King"}
			},
			"magenta":	{
				"twin":		{"id":"BSET05-T", "description":"Twin"},
				"full":		{"id":"BSET05-F", "description":"Full"},
				"queen":	{"id":"BSET05-Q", "description":"Queen"},
				"king":		{"id":"BSET05-K", "description":"King"},
				"CA_king":	{"id":"BSET05-C", "description":"California King"}
			}
		};

		if (typeof key != 'undefined') {
			if (typeof data_sets[key] != 'undefined') {
				this.category_type	= 'list';
				this.bed_type		= key;
				this.bed_id			= data_sets[this.bed_type];
			}
			else if (typeof the_look_key_mapping[key] != 'undefined') {
				this.category_type	= 'collection';
				this.bed_type		= the_look_key_mapping[key];
				this.bed_id			= data_sets[this.bed_type];
			}
		}
	}

	this.set_descriptive_data = function() {
		this.bed_title = 'Classic Whites Complete Bed';
		if		(this.bed_type === 'aqua')		{ this.bed_title += '- Aqua';	}
		else if	(this.bed_type === 'bark')		{ this.bed_title += '- Bark';	}
		else if	(this.bed_type === 'grass')		{ this.bed_title += '- Grass';	}
		else if	(this.bed_type === 'navy')		{ this.bed_title += '- Navy';	}
		else if	(this.bed_type === 'magenta')	{ this.bed_title += '- Berry';}

		if ( (this.bed_type === 'aqua') || (this.bed_type === 'bark') || (this.bed_type === 'grass') || (this.bed_type === 'navy') || (this.bed_type === 'magenta') ) {

			if (this.category_type	=== 'collection') {
				this.bed_description = '';
				this.bed_description += '<p></p>';
				this.bed_description += '<div class="displayDescription_container">';
				this.bed_description += '  <div class="summary_content_off">';
//				this.bed_description +=		$('<div/>').text('For those who crave a quieter bed, the beautiful layering pieces in our Classic Whites collection work together to create a look that is basic, and anything but boring. Border Frame Duvet and Shams feature a crisp 1" band in accent color. Gobi Embroidered Sheets are marked by graphic �knot� design. All pieces are luxurious 300-thread-count 100% cotton sateen. Buy all components together and save.').html();
				this.bed_description += '    For those who crave a quieter bed, the beautiful layering pieces in our Classic Whites collection work together to create a look that is basic, and anything but boring. Border Frame Duvet and Shams feature a crisp 1&quot; band in accent color. Gobi Embroidered Sheets are marked by graphic &ldquo;knot&rdquo; design. All pieces are luxurious 300-thread-count 100% cotton sateen. Buy all components together and save.';
				this.bed_description += '    <div class="hover_teaser_off"><span class="hover_teaser_message">&hellip; more &gt;</span></div>';
				this.bed_description += '  </div>';
				this.bed_description += '  <div class="hover_content_off">';
				this.bed_description += '    Each Complete Bed set includes:';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>TWIN: Border Frame Duvet-Twin, one Border Frame Standard Sham, one Border Frame Euro Sham, and Gobi Embroidered Sheet Set-Twin (includes flat & fitted sheets, one standard pillow case)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>FULL: Border Frame Duvet-F/Q, two Border Frame Standard Shams, two Border Frame Euro Shams, and Gobi Embroidered Sheet Set-Full (includes flat & fitted sheets, two standard pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>QUEEN: Border Frame Duvet-Queen, two Border Frame Standard Shams, two Border Frame Euro Shams, and Gobi Embroidered Sheet Set-Queen (includes flat & fitted sheets, two standard pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>KING: Border Frame Duvet-King/Cal King, three Border Frame Standard Shams, three Border Frame Euro Shams, and Gobi Embroidered Sheet Set-King (includes flat & fitted sheets, two king pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>CAL KING: Border Frame Duvet-King/Cal King, three Border Frame Standard Shams, three Border Frame Euro Shams, and Gobi Embroidered Sheet Set-Cal King (includes flat & fitted sheets, two king pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '  </div>';
				this.bed_description += '</div>';
				this.bed_description += '<p></p>';
			}

			if (this.category_type	=== 'list') {
				this.bed_description = '';
//				this.bed_description += '<p></p>';
				this.bed_description += '<div class="displayDescription_container">';
				this.bed_description += '  <div class="summary_content_off">';
//				this.bed_description +=		$('<div/>').text('All pieces are luxurious 300-thread-count 100% cotton sateen. Buy everything together and save.').html();
				this.bed_description += '    All pieces are luxurious 300-thread-count 100% cotton sateen. Buy everything together and save.';
				this.bed_description += '    <div class="hover_teaser_off"><span class="hover_teaser_message">&hellip; more &gt;</span></div>';
				this.bed_description += '  </div>';
				this.bed_description += '  <div class="hover_content_off">';
				this.bed_description += '    Each Complete Bed set includes:';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>TWIN: Border Frame Duvet-Twin, one Border Frame Standard Sham, one Border Frame Euro Sham, and Gobi Embroidered Sheet Set-Twin (includes flat & fitted sheets, one standard pillow case)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>FULL: Border Frame Duvet-F/Q, two Border Frame Standard Shams, two Border Frame Euro Shams, and Gobi Embroidered Sheet Set-Full (includes flat & fitted sheets, two standard pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>QUEEN: Border Frame Duvet-Queen, two Border Frame Standard Shams, two Border Frame Euro Shams, and Gobi Embroidered Sheet Set-Queen (includes flat & fitted sheets, two standard pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>KING: Border Frame Duvet-King/Cal King, three Border Frame Standard Shams, three Border Frame Euro Shams, and Gobi Embroidered Sheet Set-King (includes flat & fitted sheets, two king pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '    <div class="li_container">';
				this.bed_description += '    	<div class="li">&nbsp;</div>';
				this.bed_description += '    	<div>CAL KING: Border Frame Duvet-King/Cal King, three Border Frame Standard Shams, three Border Frame Euro Shams, and Gobi Embroidered Sheet Set-Cal King (includes flat & fitted sheets, two king pillow cases)</div>';
				this.bed_description += '    </div>';
				this.bed_description += '  </div>';
				this.bed_description += '</div>';
				this.bed_description += '<p></p>';
			}

		}
	}

	// ============================================================================================
}
