if ( 'undefined' != typeof jQuery )
jQuery(function(j) {
	var aURL = cartAjaxPath || '/ajax.php',
	
	addEvent = function( obj, type, fn ) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent)
			obj.attachEvent('on' + type, function() { return fn.call(obj, window.event);});
	},

	/**
	 * Get the object that was the target of an event
	 * @param object e The event object (or null for ie)
	 * @return object The target object.
	 */
	getEventTarget = function(e) {
		e = e || window.event;
		return e.target || e.srcElement;
	},

	loadingImg = new Image();
	loadingImg.src = loadingPath;
	/**
	 * Make sure that the registration form required fields have been filled.
	 * @param obj The registration form object.
	 * @param msgObj The object to which to append the resp message.
	 */
	var validateRegistrationForm = function(obj, msgObj) {
		j('#reg-error-msg').html('');
		var error = false;
		var reqFields = {
			'add_1'		: 'Address',
			'emailaddr'	: 'Email Address',
			'firstName' 	: 'First Name',
			'lastName'	: 'Last Name',
			'phone'		: 'Telephone',
			'postcode'	: 'Postcode',
			'town'		: 'Town'
		}
		for ( var i in reqFields ) {
			var obj = document.getElementById(i);
			if ( obj && '' == j('#'+i).val() ) {
				j('#'+i)
					.bind('change', function(e) {
						var that = this;
						if ( '' != j(that).val() )
							j(that).parent().removeClass('unfilled-req');
					})
					.parent().addClass('unfilled-req')
				j('#reg-error-msg').append('<p>Required Field: ' + reqFields[i] + '</p>');
				error = true;
			}
		}
		if ( '' == j('#password').val() || j('#password').val() != j('#passwordConf').val() ) {
			error = true;
			j('#password').parent().addClass('unfilled-req');
			j('#passwordConf').parent().addClass('unfilled-req');
			j('#reg-error-msg').append('<p>Enter your desired password twice</p>');
		}
		return ! error;
	}

	var submitRegistrationForm = function(obj, msgObj) {
		// submit ajaxily 
		var data = {},
		url = ajaxPath + '?do=register';
		j('input', obj).each(function(i, el) {
			data[j(el).attr('name')] = j(el).val();	
		});
		j('select', obj).each(function(i, el) {
	//		data[j(el).attr('name')] = j(el).val();	
			data[el.getAttribute('name')] = el.value;
		});
		j.post(url, data, function(resp) {
			// success
			if ( 1 == resp ) {
				
				/* get the cart contents with the order number */
				j.post(ajaxPath + '?get=global&globalName=cart&_a=step3&ajaxStatus=loggedin&orderNoRequest=1', data, function(resp) {
					var order_id = document.getElementById('cart-order-id');
					if ( ! order_id ) {
						order_id = document.createElement('input');
						order_id.setAttribute('id', 'cart-order-id');
						order_id.setAttribute('name', 'cart-order-id');
						order_id.setAttribute('type', 'hidden');
						obj.appendChild(order_id);
					}
					order_id.value = resp;

					// set the action to make a payment
					obj.setAttribute('action', 'index.php?_g=co&_a=step3&process=1&cart_order_id=' + resp);
					
					// update user meta with new user's stuff, if applicable
					replaceUsermeta();

					// refresh the payment form (with updated total cost)
//					j('#ajax-payment-form').load(ajaxPath + '?get=payment');
					
					/* get the shipping data for someone with this address */
					j.get(ajaxPath + '?get=shipping', function(resp) {
						togglePaymentForm('enable');
						updateShipping(resp, 'first-time');
					});
					var submitButton = document.getElementById('submit-ajax-reg');
					var responseWrap = document.getElementById('shipping-resp-wrap');
					if ( submitButton && ! responseWrap ) {
						responseWrap = document.createElement('div');
						responseWrap.id = 'shipping-resp-wrap';
						submitButton.parentNode.insertBefore(responseWrap, submitButton);
					}
					responseWrap.appendChild(loadingImg);
					
				});

			// error
			} else {
				j(msgObj).fadeOut().append('<div>' + resp + '</div>').fadeIn();
			}
		}, 'html');

	}

	/**
	 *  Get the latest shipping markup
	 */
	var updateShipping = function(re, first) {
		first = first || false;
		var submitButton = document.getElementById('submit-ajax-reg');
		if ( submitButton ) {
			var responseWrap = document.getElementById('shipping-resp-wrap');
			if ( ! responseWrap ) {
				responseWrap = document.createElement('div');
				responseWrap.id = 'shipping-resp-wrap';
				submitButton.parentNode.insertBefore(responseWrap, submitButton);
			}
			responseWrap.innerHTML = re;
			var shippingSelect = document.getElementById('shipping-select');
			if ( shippingSelect ) {
				var shippingSelectSubmit = function() {
					// submit newly-selected shipping
					// j.post('index.php?_g=co&_a=step2', {'ajaxify':1, 'shipKey':shippingSelect.value}, function() {
					j.post(ajaxPath + '?get=shipping', {'ajaxify':1, 'shipKey':shippingSelect.value}, function() {
						j.get(ajaxPath + '?get=shipping', updateShipping);
					});
					shippingSelect.style.display = 'none';
					shippingSelect.parentNode.insertBefore(loadingImg, shippingSelect);

				}
				shippingSelect.onchange = shippingSelectSubmit;
				// need to submit shipping the first time it appears, or else it doesn't get applied to the cart
				if ( 'first-time' == first ) {
					shippingSelectSubmit();
				}

			}
		}
	}

	/*
	 * Replace the main contents with ajaxy responses
	 * @param string resp The resp to replace with
	 */
	var replaceContent = function(resp) {
		j('#ContentBox')
			.fadeOut('slow', function() {
				j(this)
					.addClass('ajax-resp-content')
					.html(resp)
					.fadeIn('slow', assignFormEvents);
				replaceUsermeta();
			});
	}

	/*
	 * Update the usermeta data (ie, link to cart, login/out, etc.)
	 */
	var replaceUsermeta = function() {
		j.ajax({
			dataType:'html',
			type:'GET',
			success:function(userMeta) {
				// update cart ajaxily
				j('#main-user-meta')
					.html('')
					.append(userMeta)
					.fadeOut()
					.fadeIn()
					.fadeOut()
					.fadeIn();
			},
			url:ajaxPath + '?get=box&boxName=userMeta'
		});
	}

	var assignFormEvents = function() {
		/* the forms have as action the currently requested page, so let's remove that when it's from ajax */
		j('form').each(function(i, el) {
			var action = j(el).attr('action');
			if ( -1 != action.indexOf('ajax.php') )
				j(el).attr('action', '');
		});

		j('#cart-checkout').click(function(e) {
			j('#cart-checkout').parent().html(loadingImg);
			j.ajax({
				type: "GET",
				url: aURL,
				success: function(resp) {
					replaceContent(resp);
				}

			});
			return false;
		});


		j('#forgot-pass-form').submit(function(e) {
			var email = j('#forgot-pass-email').val();
			j.ajax({
				data:{email:email, submit:'Send Password'},
				dataType:'html',
				success:function(resp) {
					j('#ContentBox .login-main').fadeOut().html(resp).fadeIn();
					assignFormEvents();
					return false;
				},
				type:'POST',
				url: ajaxPath + '?get=content&contentName=forgotPass'
			});
			return false;
		});

/*
		j('#forgot-pass-link').click(function(e) {
			// get forgotten-password form
			j('#ContentBox .login-main').fadeOut().load('/ajax.php?get=content&contentName=forgotPass', assignFormEvents).fadeIn();
			return false;
		});
		*/

		// setup the shipping dropdown
		j('#shipping-select').change(function(e) {
			j('#shipkey-field').val(j(this).val());
		});
		j('#shipkey-field').val(j('#shipping-select').val());

		// quickbuy form submit event
		j('#quickBuy').submit(function(e) {
			var that = this,
			productCode = j('#productCode').val();
			j('#quickBuy').html(loadingImg);
			j.ajax({
				data:{productCode:productCode},
				success:function(resp) {
					replaceContent(resp);
				},
				type:j(that).attr('method'),
				url:ajaxPath + '?get=content&contentName=cart&ajaxStatus=loggedin'
			});
			return false;
		});
		
		// remove links events
		j('.remove-product-link').click(function(e) {
			var that = this;
			j.ajax({
				success:function(resp) {
					// delete that row
					j(that).parent().parent().fadeOut();
					replaceUsermeta();
				},
				url:j(that).attr('href')
			});
			return false;
		});

		// registration form submit event
		j('#registration-form').submit(function(){
			if ( validateRegistrationForm(j('#registration-form').get(0),j('#reg-error-msg').get(0)) ) {
				j('#submit-ajax-reg').parent().html(loadingImg);
			} else {
				// return false if validation fails
				return false;
			}
		});

		/* disable payment form unless someone agrees to terms */
		var contentBox = document.getElementById('ContentBox');
		if ( contentBox ) {
			addEvent(contentBox, 'click', eventClickContentBox);
		}
	}

	var eventClickContentBox = function(e) {
		e = e || window.event;
		var target = getEventTarget(e);
		if ( target && target.id && 'tandc' == target.id ) {
			if ( target.checked && validateRegistrationForm(document.getElementById('registration-form'),document.getElementById('reg-error-msg')) ) {
				// let's create an order if it doesn't exist
				var order_id = document.getElementById('cart-order-id');
				if ( ! order_id || '' == order_id.value ) {
					submitRegistrationForm(document.getElementById('registration-form'), document.getElementById('reg-error-msg'));
				}
				
				togglePaymentForm('enable');
				var submitButton = document.getElementById('submit-ajax-reg'),
				loadingWrap = document.createElement('div');
				loadingWrap.id = 'temp-loading-wrap';
				loadingWrap.appendChild(loadingImg);
				submitButton.parentNode.appendChild(loadingWrap);
				
			} else {
				togglePaymentForm('disable');
				target.checked = false;
			}
		}
	}

	var togglePaymentForm = function(type) {
		type = type || 'enable';
		var ajaxPayment = document.getElementById('ajax-payment-form');
		var opac = 'enable' == type ? 1 : .4;
		var filterOpac = 'enable' == type ? 100 : 40;
		if ( ajaxPayment ) {
			// ajaxPayment.style.opacity = opac;
			// ajaxPayment.style.filter = 'alpha(opacity='+filterOpac+')';
			// var inputs = ajaxPayment.getElementsByTagName('input');
			// var selects = ajaxPayment.getElementsByTagName('select');
			var submitButton = document.getElementById('submit-ajax-reg');
			var loadingWrap = document.getElementById('temp-loading-wrap');
			if ( loadingWrap ) {
				loadingWrap.parentNode.removeChild(loadingWrap);
			}
			// var items = [ inputs, selects, [submitButton] ];
			var items = [ [submitButton] ];
			for ( var j = 0; j < items.length; j ++ ) {
				var arr = items[j];
				if ( arr ) {
					for ( var i = 0; i < arr.length; i++ ) {
						if ( ! arr[i] )
							continue;
						if ( 'enable' == type ) {
							if ( arr[i].getAttribute('disabled') )
								arr[i].removeAttribute('disabled');
						} else {
							arr[i].setAttribute('disabled', 'disabled');	
						}
					}
				}
			}
		}
	}

	// set up the page initially
	assignFormEvents();
});

