var fionaturley = {
	Orders : {
		Delete:function() {
			var confirmation = confirm("Are you sure you want to delete this order?");
			if( confirmation ) {
				return true;
			} else {
				return false;
			}
		}
	},
	Forms : {
		HAL:function(id) {
			new Effect.Highlight($(id));
			$(id).focus();
		},		
		ContactUs : {
			Validate:function() {
				if( $("contactName").value.blank() ) {					
					fionaturley.Forms.HAL("contactName");
					return false;
				}
				if( $("contactEmail").value.blank() ) {					
					fionaturley.Forms.HAL("contactEmail");
					return false;
				}
				if( $("contactEmail").value.indexOf(".")==-1 || $("contactEmail").value.indexOf("@")==-1 ) {					
					fionaturley.Forms.HAL("contactEmail");
					alert("Please enter a valid email address");
					return false;
				}
				if( $("contactPhone").value.blank() ) {					
					fionaturley.Forms.HAL("contactPhone");
					return false;
				}
				if( $("yourEnquiry").value.blank() ) {					
					fionaturley.Forms.HAL("yourEnquiry");
					return false;
				}
				return true;
			}
		}
	},
	HomePageWidget : {		
		Start:function( argSlideSpeed , argSlideFadeSpeed ) {
			new Protofade( "bannerSlides" , { Delay:argSlideSpeed,Duration:argSlideFadeSpeed });
		}		
	},
	
	
	Brands : {
		Previous:function(index,count) {
			var brandIndex = index-1;
			if( brandIndex == 0 ) {
				brandIndex = count;
			}
			$("brand"+index).hide();
			$("brand"+brandIndex).show();
		},
		Next:function(index,count) {
			var brandIndex = index+1;
			if( brandIndex > count ) {
				brandIndex = 1;
			}
			$("brand"+index).hide();
			$("brand"+brandIndex).show();
		}
	},
	
	FavouriteProducts : {
		Previous:function(index,count) {
			var favouriteProductIndex = index-1;
			if( favouriteProductIndex == 0 ) {
				favouriteProductIndex = count;
			}
			$("favouriteProduct"+index).hide();
			$("favouriteProduct"+favouriteProductIndex).show();
		},
		Next:function(index,count) {
			var favouriteProductIndex = index+1;
			if( favouriteProductIndex > count ) {
				favouriteProductIndex = 1;
			}
			$("favouriteProduct"+index).hide();
			$("favouriteProduct"+favouriteProductIndex).show();
		}
	}
	
	,AddToCart:function() {
		$("addToCartButton").disabled=true;
		document.addToCartForm.submit();								
	},
	
	Products : {
		ShowTellAFriend:function(productId) {
			var url = "index.cfm?action=Ajax_Products_TellAFriend&pId=" + productId;
			new Ajax.Request( url, {asynchronous:true, onSuccess:fionaturley.Products.ShowTellAFriend_onSuccess, onFailure:errFunc});
		},
		ShowTellAFriend_onSuccess:function(t) {
			z = parseJSON( t.responseText );
			LightboxHolder.DestroyCreate("LightboxHolder");		
			$("LightboxHolder").update( z.formHTML );
			DCLightbox.showBoxByID( "LightboxHolder", 680 , 550, false );
		},
		ValidateTellAFriend:function() {
			if( $("customer_firstName").value.blank() ) {
				fionaturley.HAL("customer_firstName");
				return false;
			}
			if( $("customer_emailAddress").value.blank() || $("customer_emailAddress").value.indexOf("@") == -1 || $("customer_emailAddress").value.indexOf(".") == -1 ) {
				fionaturley.HAL("customer_emailAddress");
				return false;
			}			
			if( $("friend_name").value.blank() ) {
				fionaturley.HAL("friend_name");
				return false;
			}	
			if( $("friend_emailAddress").value.blank() || $("friend_emailAddress").value.indexOf("@") == -1 || $("friend_emailAddress").value.indexOf(".") == -1 ) {
				fionaturley.HAL("friend_emailAddress");
				return false;
			}
			$("btn_enquire").disabled = true;
			new Ajax.Request('index.cfm', {asynchronous:true, onSuccess:fionaturley.Products.ValidateTellAFriend_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "tellAFriendForm" ) )});
			return false;
		},
		ValidateTellAFriend_onSuccess:function(t) {
			z = parseJSON( t.responseText );
			alert( z.message );
			if( z.status == "OK" ) {
				Keanes.Products.Close();
			}			
		},
		Enquiry:function(productId) {
			var url = "index.cfm?action=Ajax_Products_Enquiry&pId=" + productId;
			new Ajax.Request( url, {asynchronous:true, onSuccess:fionaturley.Products.Enquiry_onSuccess, onFailure:errFunc});
		},		
		Enquiry_onSuccess:function(t) {
			z = parseJSON( t.responseText );
			LightboxHolder.DestroyCreate("LightboxHolder");		
			$("LightboxHolder").update( z.formHTML );
			DCLightbox.showBoxByID( "LightboxHolder", 680 , 550, false );
		},
		Validate:function() {
			if( $("customer_firstName").value.blank() ) {
				fionaturley.HAL("customer_firstName");
				return false;
			}
			if( $("customer_lastName").value.blank() ) {
				fionaturley.HAL("customer_lastName");
				return false;
			}	
			if( $("customer_emailAddress").value.blank() || $("customer_emailAddress").value.indexOf("@") == -1 || $("customer_emailAddress").value.indexOf(".") == -1 ) {
				fionaturley.HAL("customer_emailAddress");
				return false;
			}
			if( $("customer_message").value.blank() ) {
				fionaturley.HAL("customer_message");
				return false;
			}
			$("btn_enquire").disabled = true;
			new Ajax.Request('index.cfm', {asynchronous:true, onSuccess:fionaturley.Products.Validate_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "productEnquiryForm" ) )});
			return false;
		},
		Validate_onSuccess:function(t) {
			z = parseJSON( t.responseText );
			if( z.message ) {
				alert( z.message );
			}
			fionaturley.Products.Close();
		},
		Close:function() {
			LightboxHolder.RemoveAndClose("LightboxHolder");
		}		
	}
}


var Protofade = Class.create({

	initialize: function(element, options) {		
		this.options = {
      		Duration: 1,
			Delay: 4.0,
			Random: false,
			Slideshow:true,
			Controls:false
    	}
		Object.extend(this.options, options || {});

    	this.element        = $(element);
		this.slides			= this.element.childElements();
		this.num_slides		= this.slides.length;		
		this.current_slide 	= (this.options.Random) ? (Math.floor(Math.random()*this.num_slides)) : 0;
		this.end_slide		= this.num_slides - 1;
		
		this.slides.invoke('hide');
		this.slides[this.current_slide].show();
				
		if (this.options.Slideshow) { 
			this.startSlideshow();
		}				
		if (this.options.Controls) {
			this.addControls();
		}		
	},
	
	addControls: function() {
		this.wrapper 		= this.element.up();
		this.controls		= new Element('div', { 'class': 'controls' });
		this.wrapper.insert(this.controls);
		
		this.btn_next 		= new Element('a', { 'class': 'next', 'title': 'Next', href: '#' }).update('Next');
		this.btn_previous	= new Element('a', { 'class': 'previous', 'title': 'Previous', href: '#' }).update('Previous');
		this.btn_start		= new Element('a', { 'class': 'start', 'title': 'Start', href: '#' }).update('Start');
		this.btn_stop		= new Element('a', { 'class': 'stop', 'title': 'Stop', href: '#' }).update('Stop');
		
		this.btns = [this.btn_next, this.btn_previous, this.btn_start, this.btn_stop];
		this.btns.each(function(el){
			this.controls.insert(el);
		}.bind(this));
		
		this.btn_previous.observe('click', this.moveToPrevious.bindAsEventListener(this));
		this.btn_next.observe('click', this.moveToNext.bindAsEventListener(this));
		this.btn_start.observe('click', this.startSlideshow.bindAsEventListener(this));
		this.btn_stop.observe('click', this.stopSlideshow.bindAsEventListener(this));
	},

	startSlideshow: function(event) {
		if (event) { Event.stop(event); }
		if (!this.running)	{
			this.executer = new PeriodicalExecuter(function(){
	  			this.updateSlide(this.current_slide+1);
	 		}.bind(this),this.options.Delay);
			this.running=true;
		}
	},
	
	stopSlideshow: function(event) {	
		if (event) { Event.stop(event); } 
		if (this.executer) { 
			this.executer.stop();
			this.running=false;
		}	 
	},

	moveToPrevious: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide-1);
	},

	moveToNext: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide+1);
	},
	
	updateSlide: function(next_slide) {
		
		if (next_slide > this.end_slide) { 
				next_slide = 0; 
		} 
		else if ( next_slide == -1 ) {
				next_slide = this.end_slide;
		}
		
		this.fadeInOut(next_slide, this.current_slide);		
	},

 	fadeInOut: function (next, current) {		
		this.slides[current].setStyle({"zIndex":1});
		this.slides[next].setStyle({"zIndex":100});
		new Effect.Parallel([
			new Effect.Fade(this.slides[current], { sync: true }),
			new Effect.Appear(this.slides[next], { sync: true }) 
  		], { duration: this.options.Duration });
		
		this.current_slide = next;		
	}

});

String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\ï¿½]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

function isNumeric(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) {
	   return false; 
	} else {
		return true;
	}
} 

function LoadingAjax(txt) {
	if(typeof(txt)=="undefined") {
		txt = "Loading...";
	}
	return "<div class='ajaxMsg' id='widgetAjaxMsg'> "+txt+"</div>";
}

function parseJSON( json ){
	var o = eval('(' + json + ')');
	if( o.redirectURL )
	{
		document.location = o.redirectURL;
		return;
	}
	if( $("message") != null ) new Element.remove( "message" );
	if( o.errMsg )
	{
		if( o.errMsgTitle == null ) o.errMsgTitle = "Error";
		if( o.errMsgTimer == null ) o.errMsgTimer = 5000;
		tw.ShowMessage( o.errMsgTitle, o.errMsg, "error", o.errMsgTimer, o.errMsgPosition );
		return o;
	}
	if( o.msgTitle || o.msg )
	{
		if( o.msgTimer == null ) o.msgTimer = 5000;
		tw.ShowMessage( o.msgTitle, o.msg, o.msgClass, o.msgTimer, o.msgPosition );
	}
	return o;
}

var errFunc = function(t) {
	var win = window.open("", "win", "width=1024,height=700,resizable=yes,scrollbars=yes,status=no"); // a window object
	win.document.open("text/html", "replace");
	win.document.write( "<html><body style='margin:0'><div style='border-bottom:1px solid #222;background:#666;padding:10px;'><h1 style='color:#FFF;margin:0;padding:0;'>Digital Crew Ajax Error</h1></div><div style='padding:10px;'>"+t.responseText.replace(/^\s+|\s+$/, '') + "</div></body></html>" );
	win.document.close();
	win.focus();
}

var ClassAdder = {
	Apply:function(e) {
		$("mainNav").select("LI").each(
			function(name,index) {
				if(index<5) {
					name.addClassName("green");
				}
			}
		);
	}
}


var Account = {
	ViewOrder:function(orderId) {
		var url = "index.cfm?action=MyAccount_ViewOrder&orderId="+orderId;
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:Account.ViewOrder_onSuccess, onFailure:errFunc});
	},
	ViewOrder_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.viewOrderHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 600, 600, false );
	}
}


var ShoppingCart = {
	ChangeProductPrice:function() {
		var price = $("customPrice").value;
		var sizeText = $("customPrice").options[ $("customPrice").selectedIndex ].getAttribute("sizetext");
		if( $("sizetext") ) {
			$("sizetext").value = sizeText;
		}
		//Change Display
		var url = "index.cfm?action=ShoppingCart_ChangeProductPrice&price=" + escape( price );
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ChangeProductPrice_onSuccess, onFailure:errFunc});
	},	
	ChangeProductPrice_onSuccess:function(t) {
		z = parseJSON( t.responseText );
		$("priceHolder").update( z.priceHTML );
		$("currencyHolder").update( z.currencyHTML );
	},
	ShowSearch:function() {
		var url = "index.cfm?action=Search_ShowBox";
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowSearch_onSuccess, onFailure:errFunc});
		return false;
	},
	ShowSearch_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.searchBoxHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 400, 400, false );
		$("searchTerm").focus();
		return false;
	},
	ValidateSearchForm:function() {
		if($("searchTerm").value.blank()) {
			ShoppingCart.HighlightAndFocus("searchTerm");
			return false;
		} else {
			return true;
		} 	
	},
	AddGiftWrap:function(origPrice,shipPrice,gwPrice) {				
		if($("shippingCountryId")) {
			shipPrice = $("shippingCountryId").options[$("shippingCountryId").selectedIndex].getAttribute("key1");
		}
		var gw = $("giftWrap").checked;
		var s = parseFloat(origPrice)+parseFloat(shipPrice)+parseFloat(gwPrice);
		var ns = parseFloat(parseFloat(origPrice)+parseFloat(shipPrice));
		if(gw) {
			$("orderTotal").value = s.toFixed(2);
			$("grandTotal").update(s.toFixed(2));
			$("finalTotal").update(s.toFixed(2));
		} else {
			$("orderTotal").value = ns.toFixed(2);
			$("grandTotal").update(ns.toFixed(2));
			$("finalTotal").update(ns.toFixed(2));
		}
		new Effect.Highlight($("grandTotal"),{startcolor:'#C6EC6A'});
		new Effect.Highlight($("finalTotal"),{startcolor:'#C6EC6A'});
	},
	UpdateShipping:function(obj,origValue) {
		var shipping = obj.value;
		var shippingId = $("shippingId").options[$("shippingId").selectedIndex].getAttribute("key");
		var url = "index.cfm?action=ShoppingCart_UpdateShippingFromCart&shippingId="+shippingId;
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.UpdateShipping_onSuccess, onFailure:errFunc});
		
		if(shipping==-1) {
			$("shippingCost").update("0.00");
			$("grandTotal").update(origValue);
		} else {
			var grandTotalValue = parseFloat(origValue)+parseFloat(shipping);
			$("shippingCost").update(parseFloat(shipping).toFixed(2));
			$("grandTotal").update(grandTotalValue.toFixed(2));
		}
	},
	UpdateShipping_onSuccess:function(t) {
		z = parseJSON(t.responseText);
	},
	RecalculateShipping:function() {
		var oldShippingGroup = cShippingGroup;
		var oldShippingCost = cShippingGroupPrice;		
		if($("shippingCountryId").value!=-1) {	
			var newShippingGroupCost = $("shippingCountryId").options[$("shippingCountryId").selectedIndex].getAttribute("key1");
			var newShippingGroup = $("shippingCountryId").options[$("shippingCountryId").selectedIndex].getAttribute("key2");			
			var newShippingCountry = $("shippingCountryId").options[$("shippingCountryId").selectedIndex].getAttribute("key3");
			$("pp1").innerHTML=newShippingGroup;
			$("pp2").update(newShippingCountry);
			$("shippingCost").update(newShippingGroupCost);
			ShoppingCart.AddGiftWrap(cTotal,parseFloat(newShippingGroupCost),gwPrice);
		}
	},
	ShowEditAccountDetails:function() {
		var url = "index.cfm?action=ShoppingCart_ShowEditAccountDetailsForm";
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowEditAccountDetails_onSuccess, onFailure:errFunc});
	},
	ShowEditAccountDetails_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.editAccountFormHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 500, 330, false );
		$("firstname").focus();
		return false;
	},
	ValidateEditAccountForm:function() {
		if($("firstname").value.blank()) {
			ShoppingCart.HighlightAndFocus("firstname");
			return false;
		} else if($("lastname").value.blank()) {
			ShoppingCart.HighlightAndFocus("lastname");
			return false;
		} else if($("customerEmail").value.blank() || !$("customerEmail").value.isEmail()) {
			ShoppingCart.HighlightAndFocus("customerEmail");
			return false;
		} else if($("customerPassword1").value.blank()) {
			ShoppingCart.HighlightAndFocus("customerPassword1");
			return false;
		} else if($("customerPassword2").value.blank()) {
			ShoppingCart.HighlightAndFocus("customerPassword2");
			return false;
		} else if($("customerPassword1").value!=$("customerPassword2").value) {
			ShoppingCart.HighlightAndFocus("customerPassword1");
			ShoppingCart.HighlightAndFocus("customerPassword2");
			return false;
		}
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateEditAccountForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "editAccountForm" ) )});		
		return false;
	},
	ValidateEditAccountForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.CloseLightBox();
	},
	ShowEditShippingDetails:function() {
		var url = "index.cfm?action=ShoppingCart_ShowEditShippingDetailsForm";
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowEditShippingDetails_onSuccess, onFailure:errFunc});
	},
	ShowEditShippingDetails_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.editShippingDetailsFormHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 500, 420, false );
		$("address1").focus();
		return false;
	}, 
	ValidateEditShippingDetailsForm:function() {
		
		if($("address1").value.blank()) {
			ShoppingCart.HighlightAndFocus("address1");
			return false;
		} else if($("city").value.blank()) {
			ShoppingCart.HighlightAndFocus("city");
			return false;
		} else if($("telephone").value.blank()) {
			ShoppingCart.HighlightAndFocus("telephone");
			return false;
		}	
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateEditShippingDetailsForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "editShippingDetailsForm" ) )});		
		return false;
	},
	ValidateEditShippingDetailsForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		
		ShoppingCart.CloseLightBox();
	},
	ChangeShippingAddress:function() {
		if($("shippingChooser").checked) {
			var url = "index.cfm?action=ShoppingCart_ChangeShippingAddress";
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ChangeShippingAddress_onSuccess, onFailure:errFunc});
		} else {
			$("shippingAddressHolder").update("&nbsp;");
			$("pp1").innerHTML=cShippingGroup;
			$("pp2").update(cShippingCountry);
			$("shippingCost").update(cShippingGroupPrice);
			ShoppingCart.AddGiftWrap(cTotal,cShippingGroupPrice,gwPrice);
		}
	},
	ChangeShippingAddress_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		$("shippingAddressHolder").update(z.shippingAddressHTML);
	},
	RemoveItem:function(key) {
		var shippingId = $("shippingId").options[$("shippingId").selectedIndex].getAttribute("key");
		var url = "index.cfm?action=ShoppingCart_RemoveItem&key="+key+"&shippingId="+shippingId;
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.RemoveItem_onSuccess, onFailure:errFunc});
		return false;
	}
	,RemoveItem_onSuccess:function(t) {
		z = parseJSON( t.responseText );
		ShoppingCart.RenderShoppingCart(z.shoppingCartHTML);
	}
	,ValidateCCNumber:function(event) {
		
	}
	,UpdateQTY:function(qty,key) {
		var obj = $("sp_qty_"+key);
		var cVal = parseInt(obj.value);
		var shippingId = $("shippingId").options[$("shippingId").selectedIndex].getAttribute("key");
		if(cVal!=0 && cVal!=qty && isNumeric(cVal)) {
			var url = "index.cfm?action=ShoppingCart_UpdateQTY&key="+key+"&qty="+cVal+"&shippingId="+shippingId;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.UpdateQTY_onSuccess, onFailure:errFunc});
		} else {
			obj.value = qty;
		}
	}
	,UpdateQTY_onSuccess:function(t) {
		z = parseJSON( t.responseText );				
		ShoppingCart.RenderShoppingCart(z.shoppingCartHTML);
	}
	,EmptyCart:function() {
		var confirmation = confirm("Are you sure you wish to remove all items from your shopping basket?");
		if(confirmation) {
			var url = "index.cfm?action=ShoppingCart_Empty";
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.EmptyCart_onSuccess, onFailure:errFunc});
		}
		return false;
	}
	,EmptyCart_onSuccess:function(t) {
		z = parseJSON( t.responseText );
		ShoppingCart.RenderShoppingCart(z.shoppingCartHTML);
	}
	,RenderShoppingCart:function(cHTML) {
		$("shoppingCartHolder").update(cHTML);	
		myLightbox = new Lightbox();		
	}
	,Checkout:function(baseHref) {
		if($("shippingId").value==-1) {
			alert("Please choose a delivery option first");
		} else {
			document.location = baseHref + "index.cfm?page=checkout";
		}
	}
	,ValidateLogin:function() {
		if($("email").value.blank() || !$("email").value.isEmail()) {
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateLogin_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "loginForm" ) )});	
			return false;
		} else if($("password").value.blank()) {
			ShoppingCart.HighlightAndFocus("password");
			return false;
		}
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateLogin_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "loginForm" ) )});		
		return false;
	},
	ValidateLogin_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		if(!z.error) {
			document.location="index.cfm?page="+z.targetURL;
		} else {
			alert(z.errorMessage);
			$("email").focus();
		}	
	},
	HighlightAndFocus:function(id,divname) {		
		new Effect.Highlight($(id),{startcolor:'#C6EC6A'});
		$(id).focus();
		if(divname != undefined){
			$(divname).show();		
		}		
	},
	ShowCreateAccountForm:function(targetURL) {
		var url = "index.cfm?action=ShoppingCart_ShowCreateAccountForm&targetURL="+targetURL;			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowCreateAccountForm_onSuccess, onFailure:errFunc});		
	},
	ShowCreateAccountForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.createAccountFormHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 500, 330, false );
		$("firstname").focus();
		return false;
	},
	ViewShippingCosts:function() {
		var url = "index.cfm?action=ShoppingCart_ViewShippingCosts";			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ViewShippingCosts_onSuccess, onFailure:errFunc});
	},
	ViewShippingCosts_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.popupHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 550, 500, false );
	},
	MoreInfo:function(key) {
		var url = "index.cfm?action=ShoppingCart_ViewMoreInfo&key="+key;			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.MoreInfo_onSuccess, onFailure:errFunc});
	},
	MoreInfo_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.popupHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 400, 300, false );
	},
	ValidateCreateAccountForm:function() {
		if($("firstname").value.blank()) {
			ShoppingCart.HighlightAndFocus("firstname");
			return false;
		} else if($("lastname").value.blank()) {
			ShoppingCart.HighlightAndFocus("lastname");
			return false;
		} else if($("customerEmail").value.blank() || !$("customerEmail").value.isEmail()) {
			ShoppingCart.HighlightAndFocus("customerEmail");
			return false;
		} else if($("customerPassword1").value.blank()) {
			ShoppingCart.HighlightAndFocus("customerPassword1");
			return false;
		} else if($("customerPassword2").value.blank()) {
			ShoppingCart.HighlightAndFocus("customerPassword2");
			return false;
		} else if($("customerPassword1").value!=$("customerPassword2").value) {
			ShoppingCart.HighlightAndFocus("customerPassword1");
			ShoppingCart.HighlightAndFocus("customerPassword2");
			return false;
		}
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateCreateAccountForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "createAccountForm" ) )});		
		return false;
	},
	ValidateCreateAccountForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		if(!z.error) {
			ShoppingCart.InitialiseLightboxHolder();
			$("LightBoxHolder").update( z.createAccountFormStep2HTML );	
			MFLightbox.showBoxByID( "LightBoxHolder", 500, 450, false );

			$("address1").focus();
		} else {
			alert(z.errorMessage);
		}
	},
	ValidateCreateAccountStep2Form:function() {
		if($("address1").value.blank()) {
			ShoppingCart.HighlightAndFocus("address1");
			return false;
		} else if($("city").value.blank()) {
			ShoppingCart.HighlightAndFocus("city");
			return false;
		} else if($("telephone").value.blank()) {
			ShoppingCart.HighlightAndFocus("telephone");
			return false;
		}
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateCreateAccountStep2Form_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "createAccountStep2Form" ) )});		
		return false;
	},
	ValidateCreateAccountStep2Form_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		document.location = "index.cfm?page="+z.targetURL;
	},
	ShowForgotPasswordForm:function() {
		var url = "index.cfm?action=ShoppingCart_ShowForgotPasswordForm";			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowForgotPasswordForm_onSuccess, onFailure:errFunc});	
	},
	ShowForgotPasswordForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);	
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.forgotPasswordFormHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 400, 250, false );
		$("emailAddress").focus();
		return false;
	},
	ValidateForgottenPasswordForm:function() {
		if($("emailAddress").value.blank() || !$("emailAddress").value.isEmail()) {
			ShoppingCart.HighlightAndFocus("emailAddress");
			return false;
		}
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateForgottenPasswordForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "forgottenPasswordForm" ) )});
		return false;
	},
	ValidateForgottenPasswordForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		if(z.error) {
			alert(z.errorMessage);
			ShoppingCart.HighlightAndFocus("emailAddress");
		} else {
			ShoppingCart.GenerateMessage(z.messageHTML);
			ShoppingCart.CloseLightBox();
		}
	},
	GenerateMessage:function(m) {
		if(!$("message")) {
			$$("div.copy")[0].insert({top:"<div onclick='ShoppingCart.HideMessage()' id='message' style='display:none'>&nbsp;</div>"});
		}				
		$("message").update(m);
		$("message").show();
	},
	HideMessage:function() {
		if($("message")) {
			new Effect.Puff($("message"));
		}
	},	
	TogglePostCode:function(obj,list) {
		var cRequired = true;
		var nArray = list.split(",");
		var val = obj.options[obj.selectedIndex].value;
		for(i=0;i<nArray.length;i++) {
			if(nArray[i]==val) {
				cRequired = false;
				break;
			}
		}
		if(!cRequired) {
			$("postCodeHolder").hide();
		} else {
			$("postCodeHolder").show();
		}
	},
	InitialiseLightboxHolder:function() {
		if(!$("LightBoxHolder")) {			
			$$("body")[0].insert("<div id='LightBoxHolder' style='display:none'>Dan</div>");			
		}
	},
	CloseLightBox:function() {
		Element.hide('box');
		Element.hide('overlay');
	},
	ChangeCC:function(obj) {
		var cc = obj.value;
		$("ccImage").src="images/creditcards/" + cc + ".png";
		switch(cc) {
			case "laser":
				$("CVVNumberHolder").hide();
			break;
			case "visa":
				$("CVVNumberHolder").show();
			break;
			case "mastercard":
				$("CVVNumberHolder").show();
			break;
			case "amex":
				$("CVVNumberHolder").show();
			break;
		}
		$("ccError").update("&nbsp;");
		$("ccNumber").focus();
	},
	ValidateCheckoutForm:function() {		
		var validated = true;				
		var cCardExpired = false;
		var cCardValidated = true;
		

		if($("shippingFirstName").value.blank()) {
			ShoppingCart.HighlightAndFocus("shippingFirstName");
			return false;
		} else if($("shippingLastName").value.blank()) {
			ShoppingCart.HighlightAndFocus("shippingLastName");
			return false;
		} else if($("shippingAddress1").value.blank()) {
			ShoppingCart.HighlightAndFocus("shippingAddress1");
			return false;
		} else if($("shippingAddress2").value.blank()) {
			ShoppingCart.HighlightAndFocus("shippingAddress2");
			return false;
		} else if($("shippingCity").value.blank()) {
			ShoppingCart.HighlightAndFocus("shippingCity");
			return false;
		}
		
		if( $("rb2") && !$("rb2").checked ) {
			//This is an account checkout
			return true;
		} else {
			// This is a credit card checkout
			cCardValidated = ShoppingCart.CheckCardNumber(true);
			cCardExpired = ShoppingCart.CheckCardExpiry();
	
			if(cCardValidated && !cCardExpired) {
				return true;
			} else {
				return false;
			}			
		}
				
	},
	ChangePaymentType:function(obj) {
		if( obj.value == "CREDITCARD" ) {
			$("accountPayment").hide();
			$("creditcardPayment").show();
		} else {
			$("accountPayment").show();
			$("creditcardPayment").hide();
		}
	},
	CheckCardNumber:function(focusElement) {
		var validated = true;
		var ccNumber = $("ccNumber").value;
		var ccType = $("cardType").value;
		
		switch(ccType) {
			case "laser":
				if(!CreditCard.IsLaser(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Not a valid Laser Card number");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
			case "visa":
				if(!CreditCard.IsVisa(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Not a valid Visa Card number");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
			case "mastercard":
				if(!CreditCard.IsMasterCard(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Not a valid Mastercard number");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
			case "amex":
				if(!CreditCard.IsAmericanExpress(ccNumber)) {
					if(focusElement) {
						ShoppingCart.HighlightAndFocus("ccNumber");
					} else {
						new Effect.Highlight("ccNumber",{startcolor:'#C6EC6A'});
					}
					$("ccError").update("Invalid American Express number");
					validated=false;
				} else {
					$("ccError").update("&nbsp;");
				}
			break;
		}
		return validated;
	},
	CheckCardExpiry:function() {
		var cCardExpired = false;
		var now = new Date();
		var expiryMonth = $("expirationMonth").value;
		var expiryYear = $("expirationYear").value;
		
		if(expiryYear<now.getFullYear()) {
			cCardExpired = true;
		} else {
			if(expiryYear==now.getFullYear() && expiryMonth<now.getMonth()) {
				cCardExpired = true;
			} else {
				cCardExpired = false;
			}
		}
		
		if(cCardExpired) {
			$("edError").update("Your card has expired");
			validated=false;
		} else {
			validated=true;
			$("edError").update("&nbsp;");
		}
		return cCardExpired;
	},
	
	ShowPersonalisedForm:function(productId) {
		var url = "index.cfm?action=ShoppingCart_ShowPersonalisedForm&id="+productId;			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowPersonalisedForm_onSuccess, onFailure:errFunc});	
	},
	ShowPersonalisedForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);	
		ShoppingCart.InitialiseLightboxHolder();
		
		$("LightBoxHolder").update(z.personalisedFormHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 450, 300, false );
		
		if( $("pname") ) {
			$("pname").focus();
		}
		
		return false;
	},	
	ValidatePersonalisedForm:function(type) {
		if( type == "BIRTHDAY" ) {
			if( $("pname").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pname");
				return false;
			}
			if( $("pname2").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pname2");
				return false;
			}
			if( $("pname2").value != $("pname").value ) {
				alert("Please make sure the Name field matches the Name Confirmation field");
				return false;
			}		
			if( $("pdob").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pdob");
				return false;
			}	
		} else {
			if( $("pname").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pname");
				return false;
			}
			if( $("pname2").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pname2");
				return false;
			}
			if( $("pname2").value != $("pname").value ) {
				alert("Please make sure the Name field matches the Name Confirmation field");
				return false;
			}		
			if( $("pdate").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pdate");
				return false;
			}
			if( $("pOccasion").value.blank() ) {
				ShoppingCart.HighlightAndFocus("pOccasion");
				return false;
			}
		}
		
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidatePersonalisedForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "PersonalizeForm" ) )});		
		return false;
	},
	ValidatePersonalisedForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		document.location = "index.cfm?page="+z.targetPage;
	},
	
	ShowChurchForm:function(targetURL) {
		var url = "index.cfm?action=ShoppingCart_ShowChurchForm&targetURL="+targetURL;			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ShowChurchForm_onSuccess, onFailure:errFunc});	
	},
	ShowChurchForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);	
		ShoppingCart.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.churchFormHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 400, 400, false );
		$("name").focus();
		return false;
	},
	
	ValidateChurchForm:function() {
		if($("name").value.blank()) {
			ShoppingCart.HighlightAndFocus("name");
			return false;
		} else if($("confirmName").value.blank()) {
			ShoppingCart.HighlightAndFocus("confirmName");
			return false;
		} else if($("name").value!=$("confirmName").value) {
			ShoppingCart.HighlightAndFocus("name");
			ShoppingCart.HighlightAndFocus("confirmName");
			return false;
		}else if($("occasion").value.blank()) {
			ShoppingCart.HighlightAndFocus("occasion");
			return false;
		}else if($("date").value.blank()) {
			ShoppingCart.HighlightAndFocus("date");
			return false;
		}else if($("confirmDate").value.blank()) {
			ShoppingCart.HighlightAndFocus("confirmDate");
			return false;
		}else if($("date").value!=$("confirmDate").value) {
			ShoppingCart.HighlightAndFocus("date");
			ShoppingCart.HighlightAndFocus("confirmDate");
			return false;
		}
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:ShoppingCart.ValidateChurchForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "churchForm" ) )});		
		return false;
	},
	ValidateChurchForm_onSuccess:function(t) {
		z = parseJSON(t.responseText);
		document.location = "index.cfm?page="+z.targetPage;
		
	}
}

var CreditCard = {
	IsVisa:function(cc) {
		if(((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4)) {
			return CreditCard.IsCreditCard(cc);
		} else {
			 return false;
		}
	},
	IsMasterCard:function(cc) {
		var firstdig = cc.substring(0,1);
		var seconddig = cc.substring(1,2);
		if((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5))) {
			return CreditCard.IsCreditCard(cc);
		} else {
			return false;
		}
	},
	IsAmericanExpress:function(cc) {
		var firstdig = cc.substring(0,1);
		var seconddig = cc.substring(1,2);
		if((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7))) {
			return CreditCard.IsCreditCard(cc);
		} else {
			return false;
		}
	},
	IsLaser:function(cc) {
		if((cc.length == 19) && isNumeric(cc)) {
			return true;
		} else {
			return false;
		}
	},
	IsCreditCard:function(st) {
		if(st.length > 19) {
			return false;
		}		
		var sum = 0; 
		var mul = 1; 
		var l = st.length;
		for(i = 0;i<l;i++) {
			digit = st.substring(l-i-1,l-i);
		    tproduct = parseInt(digit ,10)*mul;
		    if (tproduct >= 10) {
		      sum += (tproduct % 10) + 1;
		    } else {
		      sum += tproduct;
			}
		    if(mul == 1) {
		      mul++;
		    } else {
		      mul--;
			}
		}
		
		if((sum % 10) == 0) {
			return true;
		} else {
			return false;
		}
	}
}

String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

function isNumeric(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) {
	   return false; 
	} else {
		return true;
	}
} 

function LoadingAjax(txt) {
	if(typeof(txt)=="undefined") {
		txt = "Loading...";
	}
	return "<div class='ajaxMsg' id='widgetAjaxMsg'> "+txt+"</div>";
}

function parseJSON( json ){
	var o = eval('(' + json + ')');
	if( o.redirectURL )
	{
		document.location = o.redirectURL;
		return;
	}
	if( $("message") != null ) new Element.remove( "message" );
	if( o.errMsg )
	{
		if( o.errMsgTitle == null ) o.errMsgTitle = "Error";
		if( o.errMsgTimer == null ) o.errMsgTimer = 5000;
		tw.ShowMessage( o.errMsgTitle, o.errMsg, "error", o.errMsgTimer, o.errMsgPosition );
		return o;
	}
	if( o.msgTitle || o.msg )
	{
		if( o.msgTimer == null ) o.msgTimer = 5000;
		tw.ShowMessage( o.msgTitle, o.msg, o.msgClass, o.msgTimer, o.msgPosition );
	}
	return o;
}


var errFunc = function(t) {
	var win = window.open("", "win", "width=1024,height=700,resizable=yes,scrollbars=yes,status=no"); // a window object
	win.document.open("text/html", "replace");
	win.document.write( "<html><body style='margin:0'><div style='border-bottom:1px solid #222;background:#666;padding:10px;'><h1 style='color:#FFF;margin:0;padding:0;'>Teamwork Ajax Error</h1></div><div style='padding:10px;'>"+t.responseText.replace(/^\s+|\s+$/, '') + "</div></body></html>" );
	win.document.close();
	win.focus();
}
var Email = {

	HighlightAndFocus:function(id,divname) {		
		new Effect.Highlight($(id),{startcolor:'#C6EC6A'});
		$(id).focus();
		if(divname != undefined){
			$(divname).show();		
		}		
	},

	ShowSendTellAFriendFrom:function(productId) {
		var url = "index.cfm?action=Email_ShowSendTellAFriendFrom&productId=" + productId;			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:Email.ShowSendTellAFriendFrom_onSuccess, onFailure:errFunc});	
	},
	ShowSendTellAFriendFrom_onSuccess:function(t) {
		z = parseJSON(t.responseText);	
		Email.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.sendTellAFriendFromHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 400, 400, false );

	},
	ValidateSendTellAFriendFrom:function(divname) {	
		if(divname != undefined){
			$(divname).hide();		
		}			
		
		if($("customer_firstName").value.blank()) {
			Email.HighlightAndFocus("customer_firstName",divname);	
			return false;
		}
		else if($("customer_emailAddress").value.blank() || !$("customer_emailAddress").value.isEmail()) {
			Email.HighlightAndFocus("customer_emailAddress",divname);
			$('submitarea').show();						
			return false;
		}
		else if($("friend_name").value.blank()) {
			Email.HighlightAndFocus("friend_name",divname);
			$('submitarea').show();						
			return false;
		}
		else if($("friend_emailAddress").value.blank() || !$("friend_emailAddress").value.isEmail()) {
			Email.HighlightAndFocus("friend_emailAddress",divname);
			$('submitarea').show();						
			return false;
		}
		
		new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:Email.ValidateSendTellAFriendFrom_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "sendTellAFriendFrom" ) )});
		return false;
	},
	ValidateSendTellAFriendFrom_onSuccess:function(t) {
		z = parseJSON( t.responseText );
		alert( z.message );
		if( z.status == "OK" ) {
			Email.CloseLightBox();
		}
	},


	InitialiseLightboxHolder:function() {
		if(!$("LightBoxHolder")) {
			$$("body")[0].insert("<div id='LightBoxHolder' style='display:none'>Dan</div>");
		}
	},
	CloseLightBox:function() {
		Element.hide('box');
		Element.hide('overlay');
	},
	GenerateMessage:function(m) {
		if(!$("message")) {
			$$("div.copy")[0].insert({top:"<div onclick='Email.HideMessage()' id='message' style='display:none'>&nbsp;</div>"});
		}
		$("message").update(m);
		$("message").show();
	},
	HideMessage:function() {
		if($("message")) {
			new Effect.Puff($("message"));
		}
	},
	
	SendTellAFriend:function(productId) {
		var url = "index.cfm?action=Email_SendTellAFriendFrom&productId=" + productId;			
		new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:Email.SendTellAFriendFrom_onSuccess, onFailure:errFunc});	
	},
	SendTellAFriendFrom_onSuccess:function(t) {
		z = parseJSON(t.responseText);	
		Email.InitialiseLightboxHolder();
		$("LightBoxHolder").update(z.sendTellAFriendFromHTML);	
		MFLightbox.showBoxByID( "LightBoxHolder", 400, 400, false );

	}

}

document.observe("dom:loaded",ClassAdder.Apply);
