var formShown = 'login';
function log() {
	if (window.console) {
		window.console.log.apply(this,arguments);
	}
}
function checkEmail(email) {
	return /^([_a-zA-Z0-9-\.]+)*@([_a-zA-Z0-9-]+)*\.([_a-zA-Z0-9-\.]+)*$/.test(email);
}
function showConfirmation(msg) {
	$.fumodal({
		content: '<div id="fumodal-popup"><div class="fu-top-left"><div class="fu-top-right"><div class="fu-top-middle"><div class="fu-left-middle"><div class="fu-right-middle"><div class="fu-bottom-left"><div class="fu-bottom-right"><div class="fu-bottom-middle"><div class="fu-content"><p class="text-center color-green size-smallest"><img id="fumodal-show-close" alt="" src="media/img/icon-close-single.png" style="float:right;cursor:pointer;" />'+msg+'</p></div></div></div></div></div></div></div></div></div></div>',
		style: false,
		backgroundColor: 'transparent',
		width: 350,
		height: 120
	});
	setTimeout($.fumodal_close,5000);
}
function showError(msg) {
	$.fumodal({
		content: '<div id="fumodal-popup"><div class="fu-top-left"><div class="fu-top-right"><div class="fu-top-middle"><div class="fu-left-middle"><div class="fu-right-middle"><div class="fu-bottom-left"><div class="fu-bottom-right"><div class="fu-bottom-middle"><div class="fu-content"><p class="text-center color-red size-smallest"><img id="fumodal-show-close" alt="" src="media/img/icon-close-single.png" style="float:right;cursor:pointer;" />'+msg+'</p></div></div></div></div></div></div></div></div></div></div>',
		style: false,
		backgroundColor: 'transparent',
		width: 350,
		height: 120
	});
	setTimeout($.fumodal_close,5000);
}
function showPopup(form) {
	var $overlayDiv = $('<div />',{
			id: 'popup-overlay',
			css: {
				top: $('#container-middle').offset().top,
				left: $('#container-middle').offset().left,
				width: $('#container-middle').outerWidth(true),
				height: $('#container-middle').outerHeight(true) + $('#container-footer').outerHeight(true)
			}
		}),
		$contentDiv = $('<div />',{
			id: 'popup-content',
			css: {
				top: $('#content-middle').offset().top,
				right: ($('body').outerWidth(true) - $('#login-register').offset().left - $('#login-register').outerWidth(true)),
				width: 600,
				height: 1
			}
		});
	if (form=='login' || form=='register') {
		formShown = form;
	} else {
		formShown = 'login';
	}
	$.post('ajax/form_logreg',{shown:formShown},function(form) {
		$overlayDiv.appendTo($('#container-middle'));
		$contentDiv.html('<div class="box-middle-left"><div class="box-middle-right"><div class="box-middle-middle">'+form+'</div></div></div><div class="box-bottom-left"><div class="box-bottom-right"><div class="box-bottom-middle"></div></div></div>');
		$contentDiv.appendTo($('#content-middle'));
		if (formShown=='login') {
			$('#popup-content .box-middle-middle').animate({height:60},500);
		} else {
			$('#popup-content .box-middle-middle').animate({height:520},500);
		}
		regCheckCountry();
		regCheckBCountry();
	});
	$('#login-register').addClass('showing');
	return false;
}
function hidePopup() {
	$('#popup-content .box-middle-middle').animate({height:0},500,function(){
		$('#popup-content').remove();
		$('#popup-overlay').remove();
	});
	$('#login-register').removeClass('showing');
	return false;
}
/*
function showAccount() {
	var $overlayDiv = $('<div />',{
			id: 'popup-overlay',
			css: {
				top: $('#container-middle').offset().top,
				left: $('#container-middle').offset().left,
				width: $('#container-middle').outerWidth(true),
				height: $('#container-middle').outerHeight(true) + $('#container-footer').outerHeight(true)
			}
		}),
		$contentDiv = $('<div />',{
			id: 'popup-content',
			css: {
				top: $('#content-middle').offset().top,
				right: ($('body').outerWidth(true) - $('#logout-account').offset().left - $('#logout-account').outerWidth(true)),
				width: 300,
				height: 1
			}
		});
	$overlayDiv.appendTo($('#container-middle'));
	$contentDiv.html('<div class="box-middle-left"><div class="box-middle-right"><div class="box-middle-middle"><table cellpadding="0" cellspacing="0" style="width:100%;"><tr><td style="width:50%;padding:5px;font-size:14px;font-weight:bold;text-align:center;"><input id="view-account" type="image" src="media/img/button-myaccount.png" /></td><td style="width:50%;padding:5px;font-size:14px;font-weight:bold;text-align:center;"><input id="logout-submit" type="image" src="media/img/button-logout.png" /></td></table></div></div></div><div class="box-bottom-left"><div class="box-bottom-right"><div class="box-bottom-middle"></div></div></div>');
	$contentDiv.appendTo($('#content-middle'));
	$('#popup-content .box-middle-middle').animate({height:40},500);
	return false;
}
function hideAccount() {
	$('#popup-content .box-middle-middle').animate({height:0},500,function(){
		$('#popup-content').remove();
		$('#popup-overlay').remove();
	});
	return false;
}
*/
function userLogin() {
	var data = {
			user: $('#logreg-login-email').val(),
			pass: $('#logreg-login-pass').val()
		};
	$.post(baseUrl+'ajax/user_login',data,function(result) {
		if (result.code) {
			window.location.reload();
		} else {
			showError('<p class="text-center color-red size-smallest">Login error.</p><p>&nbsp;</p><p class="text-left">Your login details were not matched.<br />Please verify and try again.</p>');
		}
	},'json');
	return false;
}
function userRegister() {
	var sameAddress = $('#logreg-register-sameaddress').attr('checked'),
		data = {
			first_name:	$('#logreg-register-fname').val(),
			last_name:	$('#logreg-register-lname').val(),
			email:		$('#logreg-register-email').val(),
			pass1:		$('#logreg-register-password').val(),
			pass2:		$('#logreg-register-passconf').val(),
			telephone:	$('#logreg-register-phone').val(),
			referrer:	$('#logreg-register-referrer').val(),
			// delivery address
			address1:	$('#logreg-register-address1').val(),
			address2:	$('#logreg-register-address2').val(),
			city:		$('#logreg-register-city').val(),
			county:		$('#logreg-register-county').val(),
			country:	$('#logreg-register-country option:selected').val(),
			postcode:	$('#logreg-register-postcode').val(),
			// billing address
			b_address1:	sameAddress?$('#logreg-register-address1').val():$('#logreg-register-baddress1').val(),
			b_address2:	sameAddress?$('#logreg-register-address2').val():$('#logreg-register-baddress2').val(),
			b_city:		sameAddress?$('#logreg-register-city').val():$('#logreg-register-bcity').val(),
			b_county:	sameAddress?$('#logreg-register-county').val():$('#logreg-register-bcounty').val(),
			b_country:	sameAddress?$('#logreg-register-country option:selected').val():$('#logreg-register-bcountry option:selected').val(),
			b_postcode:	sameAddress?$('#logreg-register-postcode').val():$('#logreg-register-bpostcode').val(),
			// other options
			source_id:		$('#logreg-register-source option:selected').val(),
			newsletter:	$('#logreg-register-optin').attr('checked')
		},
		messages = [];
	// check required fields
	if (data.first_name=='') {
		messages.push('Please enter your First Name');
	}
	if (data.last_name=='') {
		messages.push('Please enter your Last Name');
	}
	if (!checkEmail(data.email)) {
		messages.push('Please enter a valid Email address');
	}
	if (data.pass1.length<6) {
		messages.push('Password must be at least 6 characters long');
	}
	if (data.pass2 != data.pass1) {
		messages.push('Password doesn\'t match Confirmation');
	}
	if (data.address1=='') {
		messages.push('Please enter your Address');
	}
	if (data.city=='') {
		messages.push('Please enter your City');
	}
	if (data.country=='') {
		messages.push('Please enter your Country');
	}
	if (data.country=='US') {
		if (data.county=='') {
			messages.push('Please select your County (required for US costumers)');
		}
	}
	if (data.postcode=='') {
		messages.push('Please enter your Postcode');
	}
	// check that the billing info is set (unless sameAddress was specified)
	if (!sameAddress) {
		if ((data.b_address1=='') || (data.b_city=='') || (data.country=='') || (data.b_postcode=='')) {
			messages.push('Please fill in your Billing Address or click "Same Address" to use your Delivery Address details');
		}
		if (data.b_country=='US') {
			if (data.b_county=='') {
				messages.push('Please select your Billing County (required for US costumers)');
			}
		}
	}
	if (messages.length > 0) {
		showError('<p class="text-center color-red size-smallest">Registration form contains errors:</p><p>&nbsp;</p><p class="text-left">'+messages.join('<br />')+'</p>');
	} else {
		$.post(baseUrl+'ajax/user_add',data,function(result) {
			if (result.code) {
				showConfirmation('<p class="text-center color-green">Thank you for registering.<br />'+result.mesg+'</p>');
				window.location.reload();
			} else {
				showError(result.mesg);
			}
		},'json');
	}
	return false;
}
function regCheckCountry(e) {
	var $el = $('#logreg-register-country'),
		val = $el.val();
	if (val==='US') {
		$('#logreg-register-county').val('');
		$('#logreg-input-county').hide();
		$('#logreg-select-county').show();
	} else {
		$('#logreg-select-county').hide();
		$('#logreg-input-county').show();
	}
}
function regCheckBCountry(e) {
	var $el = $('#logreg-register-bcountry'),
		val = $el.val();
	if (val==='US') {
		$('#logreg-register-bcounty').val('');
		$('#logreg-input-bcounty').hide();
		$('#logreg-select-bcounty').show();
	} else {
		$('#logreg-select-bcounty').hide();
		$('#logreg-input-bcounty').show();
	}
}
$(function() {
	// login and register form popup
	$('#logreg-switch').live('click',function() {
		if (formShown=='login') {
			$('#logreg-switch').html('Already have an account? Click here to login.');
			$('#logreg-login-form').hide();
			$('#popup-content .box-middle-middle').animate({height:520},500,function() {
				$('#logreg-register-form').show();
			});
			formShown = 'register';
		} else {
			$('#logreg-switch').html('Don\'t have an account? Click here to register.');
			$('#logreg-register-form').hide();
			$('#popup-content .box-middle-middle').animate({height:60},500,function() {
				$('#logreg-login-form').show();
			});
			formShown = 'login';
		}
	});
	$('#logreg-login-recover').live('click', function() {
		$.fumodal({
			url: 'ajax/user_recovery',
			data: {width:350,height:150},
			style: false,
			backgroundColor: 'transparent',
			width: 350,
			height: 150
		});
		return false;
	});
	$('#logreg-login-form').live('submit', userLogin);
	$('#logreg-login-submit').live('click', userLogin);
	$('#logreg-register-password').live('keyup',function() {
		var $target	= $('#logreg-len-password'),
			passlen	= $('#logreg-register-password').val().length;
		$target.css({color:((passlen<6)?'#db5127':'#509f00')}).html('('+passlen+' characters)');
	});
	$('#logreg-register-passconf').live('keyup',function() {
		var $target	= $('#logreg-len-passconf'),
			passlen	= $('#logreg-register-passconf').val().length;
		$target.css({color:((passlen<6)?'#db5127':'#509f00')}).html('('+passlen+' characters)');
	});
	$('#logreg-register-sameaddress').live('click', function() {
		var checked = $(this).attr('checked');
		if (checked) {
			$('#logreg-register-baddress1').attr('disabled','disabled').val($('#logreg-register-address1').val());
			$('#logreg-register-baddress2').attr('disabled','disabled').val($('#logreg-register-address2').val());
			$('#logreg-register-bcity').attr('disabled','disabled').val($('#logreg-register-city').val());
			$('#logreg-register-bcounty').attr('disabled','disabled').val($('#logreg-register-county').val());
			$('#logreg-select-bcounty').attr('disabled','disabled').val($('#logreg-select-county').val());
			$('#logreg-register-bpostcode').attr('disabled','disabled').val($('#logreg-register-postcode').val());
			$('#logreg-register-bcountry').attr('disabled','disabled').val($('#logreg-register-country option:selected').val());
			regCheckBCountry();
		} else {
			$('#logreg-register-baddress1').attr('disabled','');
			$('#logreg-register-baddress2').attr('disabled','');
			$('#logreg-register-bcity').attr('disabled','');
			$('#logreg-register-bcounty').attr('disabled','');
			$('#logreg-select-bcounty').attr('disabled','');
			$('#logreg-register-bcountry').attr('disabled','');
			$('#logreg-register-bpostcode').attr('disabled','');
			regCheckBCountry();
		}
	});
	$('#logreg-select-county').live('change', function() {
		$('#logreg-register-county').val($('#logreg-select-county').val());
	});
	$('#logreg-select-bcounty').live('change', function() {
		$('#logreg-register-bcounty').val($('#logreg-select-bcounty').val());
	});
	$('#logreg-register-country').live('change', regCheckCountry);
	$('#logreg-register-bcountry').live('change', regCheckBCountry);
	$('#logreg-register-form').live('submit', userRegister);
	$('#logreg-register-submit').live('click', userRegister);
	$('#fumodal-show-close').live('click',function() {
		$.fumodal_close()
	});
	$('#view-account').live('click',function() {
		window.location.href = baseUrl+'shop/usercp';
		return false;
	});
	$('#popup-overlay').live('click',hidePopup);
	$('#login-register').click(function() {
		var isShowing = $('#login-register').hasClass('showing');
		if (isShowing) {
			hidePopup();
		} else {
			showPopup();
		}
		return false;
	});
	$('#account-link').click(function() {
		var isShowing = $('#login-register').hasClass('showing');
		if (isShowing) {
			hidePopup();
		} else {
			showPopup();
		}
		return false;
	});
	$('#logout-account').click(function() {
		$.post(baseUrl+'ajax/user_logout',{},function(result) {
			window.location.reload();
		},'json');
		return false;
	});
	$('#content-search-button').click(function() {
		var text = $('#content-search').val().replace(/[^A-Za-z0-9]/g,'-').toLowerCase();
		if (text!='') {
			window.location.href = baseUrl+'shop/search/'+text;
		}
		return false;
	});
	$('#content-search-form').submit(function() {
		var text = $('#content-search').val().replace(/[^A-Za-z0-9]/g,'-').toLowerCase();
		if (text!='') {
			window.location.href = baseUrl+'shop/search/'+text;
		}
		return false;
	});
	$('#content-shopping-bag').click(function() {
		window.location.href = baseUrl+'shop/basket';
	});
	$('#navigation-top > li').hover(function() {
		$(this).addClass('over');
	},function() {
		$(this).removeClass('over');
	});
	$('#navigation-top > li table').each(function(i,el) {
		var $el	= $(el),
			$ul	= $('#navigation-top'),
			$li	= $el.parent('li'),
			tblWidth	= $el.width(),
			ulWidth		= $ul.width(),
			uOffset	= $ul.offset().left, lOffset = $li.offset().left,
			dWidth, dOffset, offset;
		if ($el.attr('id')==='table-tips') {
			$el.css({left:-306});
		} else {
			dWidth	= Math.floor((ulWidth - tblWidth) / 2);
			dOffset	= Math.floor(uOffset - lOffset);
			offset	= dOffset + dWidth;
			$el.css({left:offset>0?0:offset});
		}
	});
});
