var SIDE_SEARCH_DEFAULT_STRING = "Search...";
var SMALL_SEARCH_DEFAULT_STRING = "Search Products...";
var cartPanel;
var cartOpacity;
var cartSize;
var currAjaxRequest;

window.addEvent("domready", function( ) {
	$E('body').addEvent("click", function(ev) { doCart(true) });
	$('cartPanel').addEvent("click", function(ev) { new Event(ev).stopPropagation( ); });
	$$('.loginout a').each(function(el) {
		el.addEvent("click", function(ev) {
			new Event(ev).stopPropagation( );
		});
	});

	var cartList = $E('.infoBar ul');

	if(cartList) {
		cartList.addEvent('click', function(ev) {
			doCart( );
			new Event(ev).stop( );
		});
	}

	var submit = $('sideSearchSubmit');
	if(submit) {
	
	}

	var query = $('sideSearchQuery');
	if(query) {
		query.addEvent('click', function(ev) {
			if(this.value == SIDE_SEARCH_DEFAULT_STRING) this.value='';
		});
		query.addEvent('blur', function(ev) {
			if(this.value.trim( ) == "") this.value=SIDE_SEARCH_DEFAULT_STRING;
		});
	}

	query = $E('.ssideSearchQuery');
	if(query) {
		query.addEvent('click', function(ev) {
			if(this.value == SMALL_SEARCH_DEFAULT_STRING) this.value='';
		});
		query.addEvent('blur', function(ev) {
			if(this.value.trim( ) == "") this.value=SMALL_SEARCH_DEFAULT_STRING;
		});
	}


	var cartLinks = $$('.cartLink');
	if(cartLinks) {
		cartLinks.each(function(el) {
			el.addEvent("click", function(ev) {
				new Event(ev).stop( );

				doCart( );				
			});
		});
	}

	/*var navigation = $$('.categoryNav');
	if(navigation) {
		navigation.each(function(el) {
			prepareCategoryNavigation(el);
		});
	}*/

	/* Testbed code */
	var testLink = $('testLink');
	if(testLink) {
		testLink.addEvent("click", function( ) {
			new Ajax(buildAjaxUrl(baseUrl+"shopping-basket/test-add/value="+$('testGadget').value), {
				method: 'get',
				onComplete: updateCartInfo
			}).request();
		});
	}
});

function prepareCategoryNavigation(parent) {
	if(parent) {
		var children = parent.getElements("ul");
		children.each(function(el) {
			prepareCategoryNavigation(el);
		});

		if(children) {
			parent.getElement("a").addEvent("click", function(ev) {
				new Event(ev).stop( );
				if(this.getParent( ).hasClass("selected")) this.getParent( ).removeClass("selected");
					else this.getParent( ).addClass("selected");
			});
		}
	}
}

function doCart(noShow) {
	if(cartPanel) {
		if(cartSize) cartSize.cancel( );
		if(cartOpacity) cartOpacity.cancel( );

		cartPanel = false;

		clearCartPanel( ); 
		(function( ) {
			cartSize = new Fx.Tween($('cartPanel'), "height").start(0).chain(
				function( ) { $('cartPanel').setOpacity(0); }
			);
		}).delay(150);

	} else if(!noShow) {
		if(currAjaxRequest) return;

		if(cartSize) cartSize.cancel( );
		if(cartOpacity) cartOpacity.cancel( );
		cartPanel = true;

		cartOpacity = new Fx.Tween($('cartPanel'), "opacity").start(1);
		cartSize = new Fx.Tween($('cartPanel'), "height").start(250).chain(
			function( ) { updateCartPanel( );  }
		);
	}
}

function clearCartPanel( ) {
	cartOpacity = new Fx.Tween($('cartContent'), "opacity").start(0).chain(
		function( ) { $('cartContent').setHTML(""); }
	);
}

function updateCartPanel( ) {
	new Request.HTML({
		url: buildAjaxUrl(baseUrl+"shopping-basket/"), 
		onComplete: updateCartContent
	}).get( );
}

function updateCartInfo( ) {
	new Request.JSON({
		url: buildAjaxUrl(baseUrl+"shopping-basket/cart-summary/"),
		onComplete: updateCartSummary
	}).get( );
}

function buildAjaxUrl(url) {
	url = url.trim( );

	if(url.substring(url.length - 1) == "/") url = url.substring(0, url.length - 1);

	if(sessionId && sessionName) url+="/"+sessionName+"="+sessionId;

	if(!url.match(/\.ajax\.html/))
		url = url.replace(".html", ".ajax.html");

	return url;
}

function updateCartContent(text) {
	cartOpacity = new Fx.Tween($('cartContent'), "opacity").start(0).chain(
		function( ) {	
			if(text[0]) $('cartContent').setHTML(text[0].getHTML( ));

			var forms = $('cartContent').getElements("form");
			if(forms) {
				
				forms.each(function(form) {
					var inputs = form.getElements("input");
					inputs.each(function(el) {
						el.addEvent("keypress", function(ev) {
							var e = new Event(ev);
							var valid = [
							   0, 1, 2, 3, 4,
							   5, 6, 7, 8, 9
							];

							if(e.key == "enter") {
								e.stop( );
								updateCartQuantities(form);
							} else if(!valid[e.key]) {
								e.stop( );
							}	
						});
					});

					form.addEvent("submit", function(ev) {
						new Event(ev).stop( );
						updateCartQuantities(form);
					});
				});
			}
		
			var removeLinks = $('cartContent').getElements(".removeLink");
			removeLinks.each(function(el) {
				var hrefs = el.getElements("a");
				hrefs.each(function(el2) {
					el2.addEvent("click", function(ev) {
						new Event(ev).stop( );
						ajaxRequest(el2.href);
					});
				});
			});
	
			cartOpacity = new Fx.Tween($('cartContent'), "opacity").start(1);
		}
	);
}

function ajaxRequest(href) {
	if(currAjaxRequest) {
		return;
	}

	new Fx.Tween($('cartContent'), "opacity").start(0).chain(
		function( ) {
			currAjaxRequest = 
			  new Request.HTML(
				{url: buildAjaxUrl(href), 
				onComplete: updateAjaxRequest,
				onFailure: function( ) {
					alert("Sorry, there was a problem "+
					"when removing your item.\n\nPlease "+
					"try again, or contact an "+
					"administrator if the problem persists."
					);
					updateAjaxRequest( );
				}
			}).get( );
		}
	);
}

function updateAjaxRequest( ) {
	currAjaxRequest = null;
	updateCartPanel( );
	updateCartInfo( );
}

function updateCartQuantities(form) {
	if(currAjaxRequest) return;

	form.action = buildAjaxUrl(form.action);

	new Fx.Tween($('cartContent'), "opacity").start(0).chain(function( ) {
		form.set('send', {
			method: 'post',
			onComplete: function( ) {
				updateAjaxRequest( );
			},
			onFailure: function(text) { 
				alert("Sorry, we could not update your basket. "+
				"\nPlease try again, and if the problem "+
				"persists,\ncontact a system administrator."
				);
				updateAjaxRequest( );
			}
		});			
		form.send( );
	});
}

function updateCartSummary(info) {
	
	var color = $('cartItem').getStyle("color");

	new Fx.Tween($('cartItem'), "color").start("#FFFF00").chain(function( ) {
		$('cartItem').setHTML(info.numItems);
		new Fx.Tween($('cartItem'), "color").start(color);
	});

	new Fx.Tween($('cartCost'), "color").start("#FFFF00").chain(function( ) {
		$('cartCost').setHTML(info.cost);
		new Fx.Tween($('cartCost'), "color").start(color);
	});
	
}

