/***************************************************************************************************
* Run as soon as JS is loaded - Grabs the current querystring from the URL.
* Also redirects if URL has more than the cat_id in querystring to a hashed version.
***************************************************************************************************/

// Make sure old # URLs continue to work.
if (location.hash.toString()) {
	var params = $H(location.toString().toQueryParams());	
	params.update($H(location.hash.toString().substring(1).toQueryParams()));
	window.location = 'product_list.asp?' + params.toQueryString();
}


/*History.Observer.start();

History.Registry.set({id:'page', onStateChange:function(value) { updateResults(); }, defaultValue:'1'});
History.Registry.set({id:'sort', onStateChange:function(value) { updateResults(); }});
History.Registry.set({id:'show', onStateChange:function(value) { updateResults(); }});
*/

//var ajaxCache = $A()

//if (History.get('page') == undefined) { History.set('page', 1); }

var clsCookie = Class.create({
	initialize: function() {
		this.cookies = $H();
	},

	_update: function() {
		this.cookies = $H();
		var arryCookies = $A(document.cookie.split('; '));
		arryCookies= arryCookies.invoke('split', '=');
		arryCookies.each(function(ary) {
			var key = '';
			var value = '';
			ary.each(function(str, i) {
				if (i == 0) { key += str; }
				else {
					value += str;
					if (i != ary.length-1) { value += '='; }
				}
			});
			try {
				this.cookies.set(key, $H(value.toQueryParams()));
			} catch(e) {}
		}.bind(this));
	},

	_getKey: function(hash, key) {
		if (hash.get(key) == undefined) {
			hash.keys().each(function(k) {
				if (k.toLowerCase() == key.toLowerCase()) {
					key = k;
					throw $break;
				}
			});
		}
		return key;
	},

	get: function(name, key) {
		this._update();
		name = this._getKey(this.cookies, name);
		if (this.cookies.get(name) != undefined) {
			key = this._getKey(this.cookies.get(name), key);
			return this.cookies.get(name).get(key);
		} else return undefined;
	},

	set: function(name, key, value) {
		this._update();
		name = this._getKey(this.cookies, name);	
		if (this.cookies.get(name) != undefined) {
			key = this._getKey(this.cookies.get(name), key);
			this.cookies.get(name).set(key, value);
		} else {
			this.cookies.set(name, $H({key:value}));
		}
		var date = new Date();
		date.setTime(date.getTime()+(1000*60*60*24*365*10));
		document.cookie = name+'='+this.cookies.get('cablestogo').toQueryString()+'; domain=.cablestogo.com; expires='+date.toGMTString()+'; path=/';
	},

	unset: function(name, key) {
		this._update();
		name = this._getKey(this.cookies, name);
		if (this.cookies.get(name) != undefined) {
			key = this._getKey(this.cookies.get(name), key);
		}
	}
});
var Cookie = new clsCookie();

/***************************************************************************************************
* Run as soon as DOM is loaded -
***************************************************************************************************/
document.observe("dom:loaded", function() {
	$('results').setOpacity(0);
	//updateResults();	
	
	var elem = $('subCats');
	if (elem) {
		elem.observe('change', function(event) {
			event.stop();
			var url = 'product_list.asp?cat_id=' + $F(this);
			if ($$('.display-type')[0].hasClassName("display-row")) { url += "&display=col"; }
			window.location = url;
		}.bindAsEventListener(elem));
	}

	productListOnLoad();
});

function productListOnLoad() {
	$('results').setOpacity(0);

	// Hide the GO buttons
	$$('.go').invoke('hide');

	var elem = $$('.product')[0];
	if ($$('.display-type')[0].hasClassName("display-col")) {
		elem.addClassName('col');
		elem.removeClassName('row');
	}
	var colStyles = $A();
	colStyles.push($H({'height':elem.getStyle('height'), 'width':elem.getStyle('width')}));
	colStyles.push($H({'width':elem.down('.description').getStyle('width')}));
	colStyles.push($H({'bottom':elem.down('.sku').getStyle('bottom')}));
	colStyles.push($H({'left':elem.down('.availability').getStyle('left')}));
	elem.addClassName('row');
	elem.removeClassName('col');
	var rowStyles = $A();
	rowStyles.push($H({'height':elem.getStyle('height'), 'width':elem.getStyle('width')}));
	rowStyles.push($H({'width':elem.down('.description').getStyle('width')}));
	rowStyles.push($H({'bottom':elem.down('.sku').getStyle('bottom')}));
	rowStyles.push($H({'left':elem.down('.availability').getStyle('left')}));
	if ($$('.display-type')[0].hasClassName("display-row")) {
		elem.addClassName('col');
		elem.removeClassName('row');
	}

	new Effect.Opacity('results', {
		from: 0,
		to: 1,
		duration: 0.3,
		afterFinish: function() {
			$('body_content').up().setStyle({ background: '#FFF' });
			minHeights();
		}
	});

	$$('.sort-info form select').each(function(elem) {
		elem.observe('change', function(event) {
			event.stop();
			this.up('form').submit();	
			//History.set('page', '1');
			//History.set('sort', $F(this.up('form').down('select')));
			//History.set('show', $F(this.up('form').down('select').next('select')));
			//updateResults();			
		}.bindAsEventListener(elem));
	});
	
	$$('.display-type').each(function(elem) {
		elem.observe('click', function(event) {
			event.stop();
			var effects = $A();
			if (this.hasClassName("display-col")) {
				Cookie.set('cablestogo', 'prodListDisplay', 'col');
				$$('.display-type').each(function(elem) {
					elem.addClassName('display-row');
					elem.removeClassName('display-col');
					elem.title = "Display as Rows";
				});
				var style1 = $H(colStyles[0]);
				var style2 = $H(colStyles[1]);
				var style3 = $H(colStyles[2]);
				var style4 = $H(colStyles[3]);
			} else {
				Cookie.set('cablestogo', 'prodListDisplay', 'row');
				$$('.display-type').each(function(elem) {
					elem.addClassName('display-col');
					elem.removeClassName('display-row');
					elem.title = "Display as Grid";
				});
				var style1 = $H(rowStyles[0]);
				var style2 = $H(rowStyles[1]);
				var style3 = $H(rowStyles[2]);
				var style4 = $H(rowStyles[3]);
			}
			$$('.product').each(function(elem) {
				effects.push(new Effect.Morph(elem, {
					sync: true,
					style: style1
				}));
				effects.push(new Effect.Morph(elem.down('.description'), {
					sync: true,
					style: style2
				}));
				effects.push(new Effect.Morph(elem.down('.sku'), {
					sync: true,
					style: style3
				}));
				effects.push(new Effect.Morph(elem.down('.availability'), {
					sync: true,
					style: style4
				}));
			});
			Effect.ScrollTo($$('body')[0], {
				duration: 0.2,
				afterFinish: function(){
					Effect.Queues.get('layout').each(function(effect) {
						effect.effects.each(function(effect) { effect.cancel(); });
					});
					new Effect.Parallel(effects, {
						queue: { scope: 'layout' },
						duration: 1.0,
						afterFinish: function() {
							minHeights();
						}
					});
				}
			});
		}.bindAsEventListener(elem));
	});

	/*$$('.pager a').each(function(elem) {
		elem.observe('click', function(event) {
			event.stop();
			var qryString = $H(this.href.toQueryParams());
			qryString.unset('cat_id');
			if (qryString.get('page') == undefined) { qryString.set('page', 1) }
			History.set('page', qryString.get('page'));
			updateResults();
		}.bindAsEventListener(elem));
	});*/
}

function updateResults() {
	//if (location.hash.toString().substring(1) != History.hash.toQueryString()) { location.hash = History.hash.toQueryString(); }
	
	var params = $H(location.toString().toQueryParams());	
	params.update($H(location.hash.toString().substring(1).toQueryParams()));
	//if (History.get('page') == undefined)
	if (params.get('page') == undefined) { params.set('page', 1) }
	Effect.ScrollTo($$('body')[0], { duration: 0.2 });
	$('body_content').up().setStyle({ background: '#FFF url(endeca/loader.gif) no-repeat center 80px' });
	new Effect.Opacity('results', {
		from: 1,
		to: 0,
		duration: 0.2
	});
	
	/*if (ajaxCache[params.toQueryString()] != undefined) {
		$('result-wrapper').update(ajaxCache[params.toQueryString()]);
		productListOnLoad();
	} else {*/
		new Ajax.Request('product-list/ajax-product-list.asp', {
			method: 'post',
			parameters: params,
			onSuccess: function(transport) {
				$('result-wrapper').update(transport.responseText);
				productListOnLoad();
				//ajaxCache[params.toQueryString()] = transport.responseText;
			}
		});
	//}
}

function minHeights() {
	var prods = $$('.product')
	if ($$('.display-type')[0].hasClassName("display-row")) {
		Effect.Queues.get('layout').each(function(effect) {
			effect.effects.each(function(effect) { effect.cancel(); });
		});
		var maxHeight = 0;
		var effects = $A();
		prods.each(function(elem, i) {
			elem.down('.sku').setStyle({ textAlign:'left' });
			elem.down('.sku').update("SKU: " + elem.down('.sku').innerHTML.slice(-6));
			var elemHeight = elem.down('.sizer').getHeight();
			if (elemHeight > maxHeight) { maxHeight = elemHeight; }
			if ((i + 1) % 3 == 0 || i == prods.length - 1 ) {
				$R(i-(i % 3), i).each(function(j) {
					effects.push(new Effect.Morph(prods[j], {
						sync: true,
						style: { height: maxHeight + "px" }
					}));
				});
				maxHeight = 0;
			}
		});		
		new Effect.Parallel(effects, {
			queue: { scope: 'layout' },
			duration: 0.2
		});
	} else {
		prods.each(function(elem) {
			elem.down('.sku').setStyle({ textAlign:'center' });
			elem.down('.sku').update(elem.down('.sku').innerHTML.slice(-6));
		});
	}
}