Number.extend({
	numberFormat : function(decimals, dec_point, thousands_sep) {
		decimals = Math.abs(decimals) + 1 ? decimals : 2;
		dec_point = dec_point || '.';
		thousands_sep = thousands_sep || ',';
		
		var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + '');
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) +
		(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	}
});

window.addEvent("domready", function(){
	//var links = $$("a");
	new SmoothScroll();

	new Accordion($$("#faqlist li span"), $$("#faqlist li p"), { "alwaysHide":true, "show":-1 });


	$$(".volatile").each(function(el){
		$(el).addEvent("focus", function(){
			if(this.getValue() == this.getProperty("title")) {
				this.value = "";
			}
		});
	});
	
	$$("a[rel*='external']").each(function(a){ 
		$(a).setProperty("target", "_blank");
	});

	if($("quantity")){
		$("quantity").addEvent("change", function(e){
			$("totalprice").setHTML("&pound;" + ($("productprice").getValue() * this.getValue()).numberFormat(2));
		});
	}
	
	// Create a new multibox
		this.multibox = new MultiBox('multibox', {
			showControls:false,
			useOverlay:true
		});
	
	$$("input[value=selectall]").each(function(el){
		var formID = el.id.substr(10, el.id.length);
			if($(formID)){
				el.addEvent("click", function(){
					$ES("input[type=checkbox]",$(formID)).each(function(checkBox){
						if($(checkBox).getProperty("value") != "selectall") {
							$(checkBox).checked = $(el).checked;
							//$(checkBox).fireEvent("click");
						}
					});
				});
			}
	});
	
});

window.addEvent("load", function(){

	var message = new MessageWindow();
	
	$$(".addtobasketform").addEvent("submit", function(e){
		new Event(e).stop();
		message.show("<h2>Please wait...</h2>This product is being added to your basket.");
		var form = this;
		new Ajax("/_colony/ecommerce/basket/ajaxadd.asp",{
			data: form,
			onError: function(){
				message.show("<h2>Sorry!</h2>An error occured, please try again.");
			},
			onComplete: function(response){
				var jsonObj = Json.evaluate(response);
				$("basket").replaceWith(new Element("div").setHTML(jsonObj.html).getFirst());
				if(jsonObj.status == 1) {
					message.show("<h2>Success</h2>" + jsonObj.message);
				} else {
					message.show("<h2 class=\"error\">Sorry!</h2>" + jsonObj.message);
				}
			}
		}).request();
		return false;
	});
	
});