var Menu = function(elt) { // creates a menu on #elt with it's contents in #elt-menubody
	var obj = this;
	var nav = $(elt);
	var menubody = $('#' + $(elt).attr('id') + '-menubody');
	var mouseinmenu = false;
	var menuisdown = false;
	var timer = false;
	
	var menuUp = function() {
		if( mouseinmenu ) {
			if( timer !== false ) {
				clearTimeout(timer);
				timer = false;
			}
		}
		else {
			menubody.slideUp(100);
			menuisdown = false;
			timer = false;
		}
	};

	menubody.hover(
		function() {
			mouseinmenu = true;
		},
		function() {
			mouseinmenu = false;
			timer = setTimeout(menuUp, 250);
		}
	);
	
	nav.hover(
		function() {
			if( !menuisdown ) {
				menubody.slideDown(100);
				menuisdown = true;
			}
		},
		function() {
			timer = setTimeout(menuUp, 250);
		}
	);
};

$.fn.menu = function() {
	return this.each(function() {
		var element = $(this);
		if( element.data('menu') ) {
			return;
		}

		var menu = new Menu(this);
		element.data('menu', menu);
	});
};	

var refreshwindow = function() {
	window.location = window.location;
}

var gotofront = function() {
	window.location = '/';
}

$.tools.validator.fn("[data-equals]", "Value must match $1", function(input) {
	var name = input.attr("data-equals"),
	field = this.getInputs().filter("[name=" + name + "]"); 
	return input.val() == field.val() ? true : [name]; 
});

var b_panel = '';
var s_panel = '';

var authoverlaymedplist = {
	api:			true,
	mask: 			'black',
	effect: 		'apple',
	target: 		'#overlaymed',
	closeOnClick:	false,
	onBeforeLoad: 	
		function() {
			var wrap = this.getOverlay().find(".contentWrap");
			if( this.getTrigger().attr('rel') != '' ) {
				wrap.load(this.getTrigger().attr("rel"));
			}
			else {
				wrap.load(this.getTrigger().attr("href"));
			}
		},
	onLoad:			
		function() {
			
			$('#registration').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				var form = $(this);
				$('.error-suffix').remove();
				if( !e.isDefaultPrevented() ) {
					var postdata = {
							first_name:	$('#first_name').val(),
							last_name:	$('#last_name').val(),
							emaddr:		$('#emaddr').val(),
							emconf:		$('#emconf').val(),
							pass:		$('#pass').val(),
							passconf:	$('#passconf').val(),
							phone1:		$('#phone1').val(),
							subscribe:  $('#subscribe').is(':checked') ? 'yes' : 'no',
							ageok:		$('#ageok').val(),
							privacy:	$('#privacy').is(':checked') ? 'yes' : 'no'
					};
					$.ajax({
						cache:		false,
						data:		postdata,
						datatype:	'json',
						success:	function(errors) {
										errors = eval('(' + errors + ')');
										if( errors['result'] === 'success' )  {
											if( errors['email_verification'] === 'required' ) {
												form.replaceWith('<h3>Registration accepted.</h3>' + 
													'<p>Please check your email for the activation link to complete the process.</p>');
											}
											else {
												form.after('<h3>Registration complete.</h3>');
												var subscribe = $('#subscribe').is(':checked') ? 'yes' : 'no';
												$.ajax({
													cache:		false,
													data:		{
																	lemail:		$('#emaddr').val(),
																	pword:		$('#pass').val(),
																	subscribe:	subscribe
																},
													datatype:	'json',
													success:	function(result) {
																	result = eval('(' + result + ')');
																	if( result['login'] === 'valid' )  {
																		form.after('<h3>You are now logged in.</h3>');
																		if( subscribe == 'yes' ) {
																			$.post(
																				'/account/subscribe/',
																				function() {
																					form.after('<p>You are subscribed to our newsletter</p>');
																					window.setTimeout(gotofront, 1000);
																				}
																			);
																		}
																		else {
																			window.setTimeout(gotofront, 1000);
																		}
																	} 
																	else {
																		form.after('<div class="error error-suffix">System error: not logged in.</div>');
																	}
																},
													type:		'post',
													url:		'/account/handleLogin/'
												});
											}
										} 
										else {
											form.data("validator").invalidate(errors);
											if( errors['email'] == 'auth_email_in_use' ) {
												form.after('<div class="error error-suffix">If you have lost your password please click <a href="/account/recover">here</a></div>');
											}
										}
									},
						type:		'post',
						url:		'/account/handleRegistration/'
					});
					e.preventDefault();
				}
			});
		},
		
	onBeforeClose:
		function() {
			$('.error').remove();
		},
		
	onClose:
		function() {
			$.post(
				'/account/asyncloginstring/', 
				function(data) {
						$('#loginstring').html(data);
						$('.auth-overlay').overlay(authoverlayplist);
						$('.auth-overlaymed').overlay(authoverlaymedplist);
						$('.auth-overlaysml').overlay(authoverlaysmlplist);
						$('.auth-menu').menu();
				}
			);
		}
};

var authoverlaysmlplist = {
	api:			true,
	mask: 			'black',
	effect: 		'apple',
	target: 		'#overlaysml',
	closeOnClick:	false,
	onBeforeLoad: 	
		function() {
			var wrap = this.getOverlay().find(".contentWrap");
			if( this.getTrigger().attr('rel') != '' ) {
				wrap.load(this.getTrigger().attr("rel"));
			}
			else {
				wrap.load(this.getTrigger().attr("href"));
			}
		},
	onLoad:			
		function() {
			$('#login-recover-trigger').click(function() {
				$('#login-recover-form').css('display', 'block');
			});
			
			$('#sendagain').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				var form = $(this);
				if( !e.isDefaultPrevented() ) {
					var postdata = { emaddr: $('#emaddr').val() };
					$.ajax({
						cache:		false,
						data:		postdata,
						datatype:	'json',
						success:	function(result) {
										result = eval('(' + result + ')');
										if( result['result'] === 'success' ) {
											form.replaceWith('<h3>New activation email has been sent</h3>');
											window.setTimeout(closeclick, 1000);
										}
										else {
											form.replaceWith('<h3>There\'s a problem.</h3>');
										}
									},
						type:		'post',
						url:		'/account/handleresend/'
					});
					e.preventDefault();
				}
			});
		
			$('#login').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				if( $('#do_nonjslogin').length == 0 ) {					
					var form = $(this);
					$('.error-suffix').remove();
					var refreshto = window.location;
					var gotohere = function() {
							var here = String(refreshto);
							var join = here.indexOf('join');
							if(  join >= 0 ) {
								window.location = 'http://crossroadsmusic.com/radio/bouncedj/';
							}
							else {
								window.location = refreshto;
							}
					};
					if( !e.isDefaultPrevented() ) {
						var postdata = {
								lemail:		$('#lemail').val(),
								pword:		$('#pword').val()
						};
						$.ajax({
							cache:		false,
							data:		postdata,
							datatype:	'json',
							success:	function(result) {
											result = eval('(' + result + ')');
											if( result['login'] === 'valid' )  {
												$('#login-recover-trigger').css('display', 'none');
												form.replaceWith('<h3>Login accepted.</h3>');
												window.setTimeout(gotohere, 1000);
	
											} 
											else {
												form.after('<div class="error error-suffix">Credentials are not valid. Please try again.</div>');
												form.data("validator").invalidate(result);
											}
										},
							type:		'post',
							url:		'/account/handlelogin/'
						});
						e.preventDefault();
					}
				}				
			});
			
			$('#recover').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				var form = $(this);
				$('.error-suffix').remove();
				if( !e.isDefaultPrevented() ) {
					var postdata = {
							recemail:	$('#recemail').val(),
							do_recover: $('#do_recover').val()
					};
					$.ajax({
						cache:		false,
						data:		postdata,
						datatype:	'json',
						success:	function(result) {
										result = eval('(' + result + ')');
										if( result['result'] === 'success' )  {
											form.replaceWith('<div><h4>We have sent you an email.</h4><p>This contains a link which will allow you to reset your password.</p></div>');
											window.setTimeout(gotofront, 1000);

										} 
										else {
											form.after('<div class="error error-suffix">Unknown email.</div>');
											form.data("validator").invalidate(result);
										}
									},
						type:		'post',
						url:		'/account/handlerecover/'
					});
					e.preventDefault();
				}					
			});
			
			$('#logout').validator().submit(function(e) {
				$(this).replaceWith('<h3>See you soon!</h3>');
				window.location = '/';
				e.preventDefault();
			});
			
			$('#age-form').submit(function(e) {
				e.preventDefault();
				$.post(
					'/account/set_age/',
					{ 'birth-year' : $('#birth-year').val() },
					function(data) {
						var ret = eval( '(' + data + ')' );
						if( ret === false ) {
							alert('We\'re sorry but we cannot offer you an account on crossroads.com at this time.');
							window.location = '/';
						}
						$('.close').click();
					}
				);
			});
			
		},
		
	onBeforeClose:
		function() {
			$('.error').remove();
		},
		
	onClose:
		function() {
			$.post(
				'/account/asyncloginstring/', 
				function(data) {
						$('#loginstring').html(data);
						$('.auth-overlay').overlay(authoverlayplist);
						$('.auth-overlaymed').overlay(authoverlaymedplist);
						$('.auth-overlaysml').overlay(authoverlaysmlplist);
						$('.auth-menu').menu();
				}
			);
		}
};

var authoverlayplist = {
	api:			true,
	mask: 			'black',
	effect: 		'apple',
	top:			15,
	target: 		'#overlay',
	closeOnClick:	false,
	onBeforeLoad: 	
		function() {
			var wrap = this.getOverlay().find(".contentWrap");
			if( this.getTrigger().attr('rel') != '' ) {
				wrap.load(this.getTrigger().attr("rel"));
			}
			else {
				wrap.load(this.getTrigger().attr("href"));
			}
		},
	onLoad:			
		function() {
			if( $.browser.webkit || $.browser.opera ) { // feature detection does not have this capability, must so far still use browser detection
				// the following is an elaborate ruse to make auto-fill continue to work, where display 'none' would disable that function.
				/*
				$('.form-label').css({
					display: 'block',
					width: 0,
					overflow: 'hidden',
					float: 'left',
					margin: 0
				});
				*/
			}
			
			$('#addreview').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				var form = $(this);
				$('.error-suffix').remove();
				var initial = $('#initial').val();
				if( initial.length ) {
					var rv = $('#review').val();
					if( rv.substr(0, initial.length) != initial ) {
						rv = initial + rv;
						$('#review').val(rv);
					}
				}
				if( !e.isDefaultPrevented() ) {
					var postdata = {
							userid:		$('#userid').val(),
							date:		$('#date').val(),
							product:	$('#product').val(),
							username:	$('#username').val(),
							unedit:		$('#unedit').val(),
							review:		$('#review').val()
					};
					var refreshto = window.location;
					var gotohere = function() {
										if( $.browser.msie ) {
											$('.sample').show();
										}
										window.location = refreshto;
									};
					$.ajax({
						cache:		false,
						data:		postdata,
						datatype:	'json',
						success:	function(errors) {
										errors = eval('(' + errors + ')');
										if( errors['result'] === 'success' ) {
											form.replaceWith('<h3>Thank you!</h3>');
											window.setTimeout(gotohere, 2000);
										}
										else {
											form.data("validator").invalidate(errors);
										}
									},
						type:		'post',
						url:		'/product/handleaddreview/'
					
					});
					e.preventDefault();
				}
			});
													
			$('#tabs').tabs('.panel');
			
			$('#subscribed').click(function(e) {
				var url = '/account/unsubscribe/';
				if( $(this).is(':checked') ) {
					var url = '/account/subscribe/';
				}
				$.post(url);
			});	
			
			if( $('#edit-user #tokens').val() == 0 && $('#edit-user #groups').val().search(/gold club/) < 0 ) {
				$('#edit-user label[for=tokens]').css('display', 'none');
				$('#edit-user #tokens').css('display', 'none');
			}
			
			$('#edit-user').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				var form = $(this);
				$('.error-suffix').remove();
				if( !e.isDefaultPrevented() ) {
					var postdata = {
							id:			$('#id').val(),
							type:		"user",
							first_name:	$('#first_name').val(),
							last_name:	$('#last_name').val(),
							emaddr:		$('#emaddr').val(),
							username:	$('#username').val(),
							address1:	$('#address1').val(),
							address2:	$('#address2').val(),
							city:		$('#city').val(),
							zip:		$('#zip').val(),
							state:		$('#state').val(),
							country:	$('#country').val(),
							phone1:		$('#phone1').val(),
							phone2:		$('#phone2').val(),
							subscribed: ( ($('#subscribed').is(':checked')) ? 'yes' : 'no' ),
							submit:		$('#do_user').attr('id')
					};
					var refreshto = window.location;
					var gotohere = function() {
						window.location = refreshto;
					};
					$.ajax({
						cache:		false,
						data:		postdata,
						datatype:	'json',
						success:	function(result) {
										result = eval('(' + result + ')');
										if( result['update'] === 'valid' )  {
											form.replaceWith('<h3>User information updated.</h3>');
											window.setTimeout(gotohere, 1000);
										} 
										else {
											form.after('<div class="error error-suffix">Please fix the errors shown and resubmit.</div>');
											form.data("validator").invalidate(result);
										}
									},
						type:		'post',
						url:		'/account/handleedituser/'
					});
					e.preventDefault();
				}
			});	
			
			if( $('.address-choice-fieldset').length == 0 ) {     /* FROM HERE RIGHT DOWN TO ----> */
			
	
				$('#billing-address-selector').change(function() {
					var v = $(this).val(); // 'billing-x' or 'billing-new'
					b_panel = v.substring(8); // 'x' or 'new'
					$('.billing-panel').not('#billing-id-' + b_panel).hide();
					$('#billing-id-' + b_panel).show();
				}).change();
				
				$('#billing-add-address-button').click(function() {
					b_panel = 'new';
					$('.billing-panel').not('#billing-id-' + b_panel).hide();
					$('#billing-id-' + b_panel).show();
				});
				
				$('.defaultcheckbox').change(function() {
					var wholeid = $(this).attr('id');
					var which = wholeid.substr(0, wholeid.indexOf('-'));
					var isbilling = ( which.substr(0,1) == 'b' ) ? "yes" : "no";
					var key = which.substr(1);
					var value = ( $(this).is(':checked') ) ? "yes" : "no";
					$.ajax({
						cache: 		false,
						data: 		{
										user:		$('#id').val(),
										billing:	isbilling,
										key:		key,
										value:		value
									},
						type:		'post',
						datatype:	'json',
						success:	function(result) {
									},
						url:		'/account/updatedefaultbs/'
					});
				});
	
				$('#edit-billing').validator({
					position: 'center right',
					offset: [0, 20]
				}).submit(function(e) {
					var form = $(this);
					var panel = '#b' + b_panel + '-';
					$('.error-suffix').remove();
					if( !e.isDefaultPrevented() ) {
						var postdata = {
								id:			b_panel,
								first_name:	$(panel + 'first_name').val(),
								last_name:	$(panel + 'last_name').val(),
								address1:	$(panel + 'address1').val(),
								address2:	$(panel + 'address2').val(),
								city:		$(panel + 'city').val(),
								state:		$(panel + 'state').val(),
								country:	$(panel + 'country').val(),
								zip:		$(panel + 'zip').val(),
								submit:		"do_billing"
						};
						var refreshto = window.location;
						var gotohere = function() {
							window.location = refreshto;
						};
						$.ajax({
							cache:		false,
							data:		postdata,
							datatype:	'json',
							success:	function(result) {
											result = eval('(' + result + ')');
											if( result['update'] === 'valid' )  {
												form.replaceWith('<h3>Billing information updated.</h3>');
												window.setTimeout(gotohere, 1000);
											} 
											else {
												form.after('<div class="error error-suffix">Please fix the errors shown and resubmit.</div>');
												form.data("validator").invalidate(result);
											}
										},
							type:		'post',
							url:		'/account/handleedituser/'
						});
						e.preventDefault();
					}
				});
				
				$('#shipping-address-selector').change(function() {
					var v = $(this).val();
					s_panel = v.substring(9);
					$('.shipping-panel').not('#shipping-id-' + s_panel).hide();
					$('#shipping-id-' + s_panel).show();
				}).change();
				
				$('#shipping-add-address-button').click(function() {
					s_panel = 'new';
					$('.shipping-panel').not('#shipping-id-' + s_panel).hide();
					$('#shipping-id-' + s_panel).show();
				});
				
				$('#edit-shipping').validator({
					position: 'center right',
					offset: [0, 20]
				}).submit(function(e) {
					var form = $(this);
					var panel = '#s' + s_panel + '-';
					$('.error-suffix').remove();
					if( !e.isDefaultPrevented() ) {
						var postdata = {
								id:			s_panel,
								first_name:	$(panel + 'first_name').val(),
								last_name:	$(panel + 'last_name').val(),
								address1:	$(panel + 'address1').val(),
								address2:	$(panel + 'address2').val(),
								city:		$(panel + 'city').val(),
								state:		$(panel + 'state').val(),
								country:	$(panel + 'country').val(),
								zip:		$(panel + 'zip').val(),
								submit:		"do_shipping"
						};
						var refreshto = window.location;
						var gotohere = function() {
							window.location = refreshto;
						};
						$.ajax({
							cache:		false,
							data:		postdata,
							datatype:	'json',
							success:	function(result) {
											result = eval('(' + result + ')');
											if( result['update'] === 'valid' )  {
												form.replaceWith('<h3>Shipping information updated.</h3>');
												window.setTimeout(gotohere, 1000);
											} 
											else {
												form.after('<div class="error error-suffix">Please fix the errors shown and resubmit.</div>');
												form.data("validator").invalidate(result);
											}
										},
							type:		'post',
							url:		'/account/handleedituser/'
						});
						e.preventDefault();
					}
				});
			}
			else { /* JUST ABOVE HERE ... will get replaced by the new system, eventually. The new system being what's there below... */
			
				$('.address-edit').click(function() {
					var id = $(this).attr('id');
					var chopfrom = id.lastIndexOf('-');
					var addressdiv = id.substring(0, chopfrom);
					var b_or_s = addressdiv.substring(0, addressdiv.indexOf('-'));
					var addressid = addressdiv.substring(addressdiv.lastIndexOf('-') + 1);
					if( b_or_s == 'billing' ) {
						b_panel = addressid;
					}
					else {
						s_panel = addressid;
					}
					$('#' + b_or_s + '-choice').hide();
					$('#' + addressdiv).show();
				});
				
				$('#billing-add-address-button').click(function() {
					b_panel = 'new';
					$('.billing-panel').not('#billing-id-' + b_panel).hide();
					$('#billing-id-' + b_panel).show();
				});
				
				$('.address-choice-radio').change(function() {
					var id = $(this).attr('id');
					var isbilling = (id.substring(0, id.indexOf('-')) == 'billing') ? 'yes' : 'no';
					var value = $(this).is(':checked') ? 'yes' : 'no';
					var shorten = id.substring(id.indexOf('-') + 1, id.lastIndexOf('-'));
					var key = shorten.substring(shorten.indexOf('-') + 1, shorten.length);
					var user = $('#id').val();
					$.ajax({
						cache: 		false,
						data: 		{
										user:		user,
										billing:	isbilling,
										key:		key,
										value:		value
									},
						type:		'post',
						datatype:	'json',
						success:	function(result) {
										var res = $.parseJSON(result);
										if( res ) {
											var label = $('label[for="' + id + '"]');
											var labeltext = label.text();
											label.text(label.text() + ' - default');
											var relabel = function(args) {
												$('label[for="' + args[0] + '"]').text(args[1]);
											}
											setTimeout(relabel, 1000, [id, labeltext]);
										}	
									},
						url:		'/account/updatedefaultbs/'
					});
				});					
				
				$('#edit-billing').validator({
					position: 'center right',
					offset: [0, 20]
				}).submit(function(e) {
					var form = $(this);
					var panel = '#b' + b_panel + '-';
					$('.error-suffix').remove();
					if( !e.isDefaultPrevented() ) {
						var postdata = {
								id:			b_panel,
								first_name:	$(panel + 'first_name').val(),
								last_name:	$(panel + 'last_name').val(),
								address1:	$(panel + 'address1').val(),
								address2:	$(panel + 'address2').val(),
								city:		$(panel + 'city').val(),
								state:		$(panel + 'state').val(),
								country:	$(panel + 'country').val(),
								zip:		$(panel + 'zip').val(),
								submit:		"do_billing"
						};
						var refreshto = window.location;
						var gotohere = function() {
							window.location = refreshto;
						};
						$.ajax({
							cache:		false,
							data:		postdata,
							datatype:	'json',
							success:	function(result) {
											result = $.parseJSON(result);
											if( result['update'] === 'valid' )  {
												form.replaceWith('<h3>Billing information updated.</h3>');
												window.setTimeout(gotohere, 1000);
											} 
											else {
												form.after('<div class="error error-suffix">Please fix the errors shown and resubmit.</div>');
												form.data("validator").invalidate(result);
											}
										},
							type:		'post',
							url:		'/account/handleedituser/'
						});
						e.preventDefault();
					}
				});
				
				$('#shipping-address-selector').change(function() {
					var v = $(this).val();
					s_panel = v.substring(9);
					$('.shipping-panel').not('#shipping-id-' + s_panel).hide();
					$('#shipping-id-' + s_panel).show();
				}).change();
				
				$('#shipping-add-address-button').click(function() {
					s_panel = 'new';
					$('.shipping-panel').not('#shipping-id-' + s_panel).hide();
					$('#shipping-id-' + s_panel).show();
				});
				
				$('#edit-shipping').validator({
					position: 'center right',
					offset: [0, 20]
				}).submit(function(e) {
					var form = $(this);
					var panel = '#s' + s_panel + '-';
					$('.error-suffix').remove();
					if( !e.isDefaultPrevented() ) {
						var postdata = {
								id:			s_panel,
								first_name:	$(panel + 'first_name').val(),
								last_name:	$(panel + 'last_name').val(),
								address1:	$(panel + 'address1').val(),
								address2:	$(panel + 'address2').val(),
								city:		$(panel + 'city').val(),
								state:		$(panel + 'state').val(),
								country:	$(panel + 'country').val(),
								zip:		$(panel + 'zip').val(),
								submit:		"do_shipping"
						};
						var refreshto = window.location;
						var gotohere = function() {
							window.location = refreshto;
						};
						$.ajax({
							cache:		false,
							data:		postdata,
							datatype:	'json',
							success:	function(result) {
											result = eval('(' + result + ')');
											if( result['update'] === 'valid' )  {
												form.replaceWith('<h3>Shipping information updated.</h3>');
												window.setTimeout(gotohere, 1000);
											} 
											else {
												form.after('<div class="error error-suffix">Please fix the errors shown and resubmit.</div>');
												form.data("validator").invalidate(result);
											}
										},
							type:		'post',
							url:		'/account/handleedituser/'
						});
						e.preventDefault();
					}
				});
			
			}
			
			$('#edit-password').validator({
				position: 'center right',
				offset: [0, 20]
			}).submit(function(e) {
				var form = $(this);
				if( !e.isDefaultPrevented() ) {
					$.ajax({
						cache:		false,
						data:		{
										user: 	$('#id').val(),
										old:	$('#oldpass').val(),
										pass:	$('#pass').val(),
										submit:	"do_password"
									},
						datatype:	'json',
						success:	function(result) {
										result = eval('(' + result + ')');
										if( result['update'] === 'valid' )  {
											form.replaceWith('<h3>Password Changed.</h3>');
											window.setTimeout(closeclick, 1000);
										} 
										else {
											form.after('<div class="error error-suffix">Please fix the errors shown and resubmit.</div>');
											form.data("validator").invalidate(result);
										}
									},
						type:		'post',
						url:		'/account/handleedituser/'
					});
					e.preventDefault();
				}
			});
			
			$('.deleteaddress').click(function() {
				var id = $(this).attr('id');
				var user = $('#id').val();
				var address = id.substring(1, id.indexOf('-'));
				var isbilling = (id.charAt(0) == 'b') ? 'yes' : 'no';
				$.ajax({
					cache:		false,
					data:		{
									id:			address,
									user:		user,
									isbilling:	isbilling
								},
					datatype: 	'json',
					success:	function(result) {
									result = eval('(' + result + ')');
									var loc = isbilling ? '#edit-billing' : '#edit-shipping';
									if( result['delete'] === 'valid' )  {
										$(loc).replaceWith('<h3>Address deleted.</h3>');
										window.setTimeout(closeclick, 1000);
									} 
									else {
										$('#edit-billing').after("<h3>Error</h3><h4>" + result['error'] + "</h4>");
									}
								},
					type:		'post',
					url:		'/account/deleteaddress/'
				});
			});
		},
	onBeforeClose:
		function() {
			$('.error').remove();
		},
	onClose:
		function() {
			$.post(
				'/account/asyncloginstring/', 
				function(data) {
						$('#loginstring').html(data);
						$('.auth-overlay').overlay(authoverlayplist);
						$('.auth-overlaymed').overlay(authoverlaymedplist);
						$('.auth-overlaysml').overlay(authoverlaysmlplist);
						$('.auth-menu').menu();
				}
			);
		}
};

var closeclick = function() {
	$('.close').trigger('click');
}


var ft_interval = null;
var shouldAnimateFeatured = true;
var currentfeatured = 0;
var doing_slide_in = false;
var doing_slide_out = false;


var animatefeatured = function() {
	if( shouldAnimateFeatured && !doing_slide_in && !doing_slide_out ) {
		var featured = $('.panel-feature');
		var fademeout = $(featured.get(currentfeatured));
		var nextfeatured = (currentfeatured + 1 == featured.length) ? 0 : currentfeatured + 1;
		var fademein = $(featured.get(nextfeatured));
		fademeout.fadeOut(2000, function() { });
		fademein.fadeIn(2000);
		currentfeatured = nextfeatured;
	}
}

$(document).ready(function() {

	/*
    if (window.PIE) {
        $('.panel-feature-image').each(function() {
        	PIE.attach(this);
        });
    }
	*/
	
	$('.auth-overlay').overlay(authoverlayplist);
	$('.auth-overlaymed').overlay(authoverlaymedplist);
	$('.auth-overlaysml').overlay(authoverlaysmlplist);
	
	$('.auth-menu').menu();
	
	$('#newsletterbox').click(function() {
		$(this).find('form.buybutt').submit();
	});
			
	$('#registeratcheckout').validator({
		position: 'center right',
		offset: [0, 20]
	}).submit(function(e) {
		var form = $(this);
		$('.error-suffix').remove();
		if( !e.isDefaultPrevented() ) {
			var postdata = {
					emaddr:				$('#emaddr').val(),
					emconf:				$('#emconf').val(),
					pass:				$('#pass').val(),
					passconf:			$('#passconf').val(),
					phone1:				$('#phone1').val(),
					phone2:				$('#phone2').val(),
					'b0-first_name':	$('#b0-first_name').val(),
					'b0-last_name':		$('#b0-last_name').val(),
					'b0-address1':		$('#b0-address1').val(),
					'b0-address2':		$('#b0-address2').val(),
					'b0-city':			$('#b0-city').val(),
					'b0-state':			$('#b0-state').val(),
					'b0-zip':			$('#b0-zip').val(),
					'b0-country':		$('#b0-country').val(),
					's0-first_name':	$('#s0-first_name').val(),
					's0-last_name':		$('#s0-last_name').val(),
					's0-address1':		$('#s0-address1').val(),
					's0-address2':		$('#s0-address2').val(),
					's0-city':			$('#s0-city').val(),
					's0-state':			$('#s0-state').val(),
					's0-zip':			$('#s0-zip').val(),
					's0-country':		$('#s0-country').val(),
					's0-usebilling':	( $('#s0-usebilling').is(':checked') ? 'yes' : 'no' ),
					'subscribe':		( $('#subscribe').is(':checked') ? 'yes' : 'no' ),
					'ageok':			$('#ageok').val(),
					'privacy':			$('#privacy').val()
			};
			
			$.ajax({
				cache:		false,
				data:		postdata,
				datatype:	'json',
				async:		false,	// necessary so preventDefault can take place only after this call returns validation
				success:	function(errors) {
								errors = eval('(' + errors + ')');
								if( errors['result'] === 'success' )  {
									// we don't prevent default so the submit now occurs.
								} 
								else {
									form.data("validator").invalidate(errors);
									e.preventDefault();
								}
							},
				type:		'post',
				url:		'/checkout/validateregisteratcheckoutform/'
			});
		}
	});
	
	$('#do_news').click(function() {
		$.ajax({
			cache:		false,
			data:		{ nlemail: $('#nlemail').val() },
			datatype:	'json',
			success:	function(errors) {
							errors = eval('(' + errors + ')');
							if( errors['result'] === 'success' ) {
								$('#newsletterbox').html('<h4>Done!</h4><p>You will now receive our newsletter.</p>');
							}
							else {
								alert( 'Error: ' + errors['error'] );
							}
						},
			type:		'post',
			url:		'/account/newsletter/'
		});
	});
	
	$('#login').validator({
		position: 'center right',
		offset: [0, 20]
	}).submit(function(e) {
		var form = $(this);
		$('.error-suffix').remove();
		if( !e.isDefaultPrevented() ) {
			var postdata = {
					lemail:		$('#lemail').val(),
					pword:		$('#pword').val(),
					viaajax:	'true'
			};
			$.ajax({
				cache:		false,
				data:		postdata,
				datatype:	'json',
				success:	function(errors) {
								errors = eval('(' + errors + ')');
								if( errors['result'] === 'success' )  {
									window.location = '/checkout/';
								} 
								else {
									form.data("validator").invalidate(errors);
								}
							},
				type:		'post',
				url:		'/checkout/handlelogin/'
			});
			e.preventDefault();
		}					
	});
	
	$('.cart-tokenize').click(function(e) {
		var id = $(this).attr('name').substring(9);
		var usetokens = ( $(this).val() == 'Change to tokens' ) ? 'yes' : 'no';
		if( usetokens == 'yes' && $('#token-balance').val() < $(this).parent().prev().children().html() ) {
			// the above "token cost" dom traversal relies on the table being set up just this way, so BEWARE
			alert('There are too few tokens remaining to convert this purchase to tokens.');
		}
		else {
			$.ajax({
				cache:		false,
				data:		{ id : id, usetokens: usetokens },
				datatype:	'json',
				success:	function(errors) {
								refreshwindow();
							},
				type:		'post',
				url:		'/cart/convertTokens/'
			});
		}
	});
	
	if( $('#token-balance').val() < 0 ) { // do this once at page load, in case "update" has taken token balance below zero
		$('.checkout-steps').parent().prev().after('<div class="grid_12"><div id="fmessage">Not enough tokens - please adjust your token payments before checking out.<div id="fmessageClose">X</div></div></div>');
	}
	
	$('.vc-album-download').click(function(e) {
		e.preventDefault();
		var form = $(this).parent();
		var message = $('<div class="container_6"><div id="dfmessage">We are preparing your download - <br/>this could take a minute or two.<div id="fmessageClose">X</div></div></div>');
		form.after(message);
		form.submit();
	});
	
	$('.rv-delete').click(function(e) {
		e.preventDefault();
		var id = $(this).parent().children('[name="rv-id"]').val();
		var author = $(this).parent().children('[name="rv-authorid"]').val();
		$.ajax({
				cache:		false,
				data:		{ id : id, author: author },
				datatype:	'json',
				success:	function(errors) {
								refreshwindow();
							},
				type:		'post',
				url:		'/product/handledeletereview/'
		});
	});
	
	$('.faq-popup').tooltip({
		tipClass:		'faq-tip',
		onBeforeShow: 	function() {
							var tip = this.getTip();
							var trigger = this.getTrigger();
							var faq = trigger.attr('id').substr(4);
							$.post(
								'/faq/get/',
								{ id: faq },
								function(result) {
									tip.html(result);
								}
							);
						}
	});
	
	$('#registeratcheckout #s0-usebilling').click(function() {
		if( !$(this).is(':checked') ) {
			$('#registeratcheckout #shipping label').css('display', 'inline'); 
			$('#registeratcheckout #shipping input').css('display', 'inline');
			$('#registeratcheckout #shipping select').css('display', 'inline');
			$('#registeratcheckout #shipping br').css('display', 'inline');
			$('#registeratcheckout #shipping span').css('display', 'inline');
		}
		else {
			$('#registeratcheckout #shipping label').css('display', 'none'); 
			$('#registeratcheckout #shipping input').css('display', 'none');
			$('#registeratcheckout #shipping select').css('display', 'none');
			$('#registeratcheckout #shipping br').css('display', 'none');
			$('#registeratcheckout #shipping span').css('display', 'none');
			$('#registeratcheckout #shipping label:first-child').css('display', 'inline');
			$('#registeratcheckout #shipping input#s0-usebilling').css('display', 'inline');	
		}
	});	
	
	$('#rv-add-link').click(function() {
		if( $.browser.msie ) {
			$('.sample').hide();
		}
	});
	
	$('.rv-add-link').click(function() {
		if( $.browser.msie ) {
			$('.sample').hide();
		}
	});	
	
	$('#account').click(function(e) {
		e.preventDefault();
		$('#account-edit-menuitem').trigger('click');
	});
	
	$('.group-icon').tooltip({
			relative: true,
			position: 'bottom center',
			tipClass: 'group-icon-tip',
			offset: [0,14] /*
			onBeforeShow: function(event, position){
				this.getTrigger().parent().parent().css('z-index','9999');
			},
			onHide: function(){
				this.getTrigger().parent().parent().css('z-index','1');
			}
			*/
	}); //.dynamic();
	
	// featured panel rotation etc...
	if( $('.panel-feature').length > 1 ) {
		ft_interval = setInterval('animatefeatured()', 5000);
		//$($('.panel-feature').get(currentfeatured)).css('opacity', 1);
		$($('.panel-feature').get(currentfeatured)).show();
		$('.panel-feature').click(function() {
			if( ft_interval != null ) {
				clearInterval(ft_interval);
				ft_interval = null;
			}
			// pass the click through... the span is an a link
		});	
	}
	else {
		$('.panel-feature').show();
	}
	
	/*	
	Not required at the moment
	
	$('.features-nav-right').click(function() {
		shouldAnimateFeatured = false;
		if( ft_interval != null ) {
			clearInterval(ft_interval);
			ft_interval = null;
		}
		var featured = $('.panel-feature');
		var fademeout = $(featured.get(currentfeatured));
		var nextfeatured = (currentfeatured + 1 == featured.length) ? 0 : currentfeatured + 1;
		var fademein = $(featured.get(nextfeatured));
		fademeout.fadeOut(500);
		fademein.fadeIn(500);
		currentfeatured = nextfeatured;
	});
	
	$('.features-nav-left').click(function() {
		shouldAnimateFeatured = false;
		if( ft_interval != null ) {
			clearInterval(ft_interval);
			ft_interval = null;
		}
		var featured = $('.panel-feature');
		var fademeout = $(featured.get(currentfeatured));
		var nextfeatured = (currentfeatured == 0) ? featured.length - 1 : currentfeatured - 1;
		var fademein = $(featured.get(nextfeatured));
		fademeout.fadeOut(500);
		fademein.fadeIn(500);
		currentfeatured = nextfeatured;
	});
	*/

	$('.panel-feature').hover(
		function() {						// mouse in...
			if( doing_slide_in ) {
				return;
			}
			var slider = $(this).find('.slide-text');
			if( slider.hasClass('slide-none') ) {
				return false;
			}
			doing_slide_in = true;
			if( ft_interval != null ) {
				clearInterval(ft_interval);
				ft_interval = null;
			}
			if( slider.hasClass('slide-left') ) {
				slider.css('left', '-300');
				//slider.find('.slide-handle').fadeOut('fast');
				slider.animate({ left: '0' }, 1000, function() { 
					doing_slide_in = false; 
				});
			}
			else {
				slider.css('left', '920');
				//slider.find('.slide-handle').fadeOut('fast');
				slider.animate({ left: '593' }, 1000, function() { 
					doing_slide_in = false; 
				});
			}
		},
		function() {						// mouse out...
			if( doing_slide_out ) {
				return;
			}
			var slider = $(this).find('.slide-text');
			if( slider.hasClass('slide-none') ) {
				return false;
			}
			doing_slide_out = true;
			if( ft_interval == null ) {
				if( $('.panel-feature').length > 1 ) {
					ft_interval = setInterval('animatefeatured()', 5000);
				}
			}
			if( slider.hasClass('slide-left') ) {
				slider.css('left', '0');
				slider.animate({ left: '-327' }, 1000, function() { 
					doing_slide_out = false; 
					//slider.find('.slide-handle').fadeIn('slow'); 
				});
			}
			else {
				slider.css('left', '620');
				slider.animate({ left: '947' }, 1000, function() { 
					doing_slide_out = false; 
					//slider.find('.slide-handle').fadeIn('slow'); 
				});
			}
		}
	);
	
	/* front page big buttons */
	
	$('.front-btn').hover(
		function() {
			$(this).find('.btn-overlay').show().animate({opacity: '1.0'}, 500, function() { });
		},
		function() {
			$(this).find('.btn-overlay').animate({opacity: '0.0'}, 500, function() { }).hide();
		}
	);
	
	$('#cm-btn').click(function() { window.location = '/christian/'; });
	$('#bg-btn').click(function() { window.location = '/bluegrass/'; });
	$('#perf-btn').click(function() { window.location = '/performance/'; });
	
	/* gold club add to cart */
	
	$('#goldclub-addtocard').click(function() {
		$('#cart_club_purchase_form').submit();
	});
	
	$('#tos-checkbox').click(function() {
		if( $('#tos-checkbox').is(':checked') ) {
			//$('.tos-checkout').show();
		}
		else {
			//$('.tos-checkout').hide();
			var answer = confirm("Really disagree with these terms? (Relevant items will be removed from cart)")
			if (answer){
				window.location = "/checkout/removetos/";
			}
			else {
				$('#tos-checkbox').attr('checked', 'checked');
			}
		}
	});
	
	/*
	$('#tos-checkbox').confirm({
		msg: '<span class="tos-check-span">If you do not agree the performance tracks will be removed from your cart: </span>',
		dialogShow:'fadeIn',
  		dialogSpeed:'slow',
		buttons: {
			wrapper:'<button></button>',
			separator:'  ',
			ok: 'Disagree',
			cancel: 'Agree'
		}  
	});
	*/	
	
	/* RADIO STUFF */
	
	$('form#set-default-genre').submit(function(e) {
		e.preventDefault();
		$.ajax({
			url: '/radio/ajax_set_default_genre/',
			data: { 'user-id' : $('#user-id').val(), 'set-default-as' : $('#set-default-as').val() },
			success: function(data) {
				alert('Your default has been set.');
			},
			dataType: 'json',
			type: 'post'
		});
	});
	
	$('#submit-switch').click(function(e) {
		e.preventDefault();
		genre = $('#go-to-genre').val();
		selstr = '.genre-option[value="' + genre + '"]';
		slug = $(selstr).attr('slug');
		if( typeof slug != "undefined" ) {
			$('form#switch-genre').attr('action', '/radio/' + slug +'/');
		}
		$('form#switch-genre').submit();
	});
	
	
});

var deleteMessage = function() {
	$('.temporary-message').fadeOut(1000, function() { $(this).remove(); });
}

$(window).load(function() {
	if( $('.temporary-message').length ) {
		var messagetimer = setTimeout('deleteMessage()', 10000);
	}
	
	/* CHECK AGE AND PRIVACY */
		
	if( $('#ask-user-age').length ) {
		$('#ask-user-age').click();
	}
});

