jQuery(function($) {
	
	// Set GMT offset
	bricksf.gmtOffset();
	//alert(window.location.host.match(/[\w]+\.[\w]+$/));
	// Autogrow textareas
	$('textarea').growfield();
	
	// Smooth scrollin'
	$.localScroll();
	$.localScroll.hash();
	
	// #hashtags
	$('#content a[rel="tag"]').live('click', function () {
		alert('Soon this will show other items with the same hashtag.');
		return false;
	});
	
	// Set textarea max character
	//$('textarea[maxlength]').maxLength();
	
	// Form input hints
	$('input[title], textarea[title]').inputHint();
	$('select').live('change', function() {
		if (this.value) $(this).removeClass('hint');
		else $(this).addClass('hint');
	});
	
	$('form.validate').validate();
	// Submit "button"
	$('form a.button[href$="#submit"]:not(.disabled)').live('click', function () {
		$(this).blur();
		$(this).closest('form').submit();
		return false;
	});
	// Submit form on enter/return
	$('input').live('keydown', function(e){
		if (e.keyCode == 13) {
			$(this).parents('form').submit();
			return false;
		}
	});
	
	// Show lightbox if it has content
	$('#lightbox .lightbox').parent().show();
	
	// Help non-CSS3 browsers out a bit
	$('html:not(.ie6) #content .col:last-child').addClass('last-child');
	
	// Login lightbox
	$('a[href^="/session/login"]').live('click', function () {
		$.get(this.href, {lightbox:true} ,function (data) {
			$('#lightbox').html(data).fadeIn(400);
			custom.login();
		});
		return false;
	});
	$('#login a[href$="#forgot_password"]').live('click', function () {
		if ((userEmail = $('#login input[name="email"]').val().match(/[\w]+@[\w]+\.[\w]+/)) && (userEmail != $('#login input[name="email"]').attr('title'))) {
			$.getJSON('/user/forgot_password', { email: userEmail, referer: escape(window.location) }, function(json) {
				if (json.error) {
					$('#login_response').addClass('error').html(json.message);
					$('#login input[name="email"]').focus();
				} else {
					$('#login_response').removeClass('error').html(json.message);
					//$('#login a[href$="#forgot_password"]').addClass('disabled');
				}
			});
		} else {
			$('#login input[name="email"]').focus();
			$('#login_response').addClass('error').html('Enter your email address');
		}
		return false;
	});
	if ($('#lightbox .lightbox_login').length) {
		custom.login();
	}
	if ($('#lightbox .lightbox_rpx').length) {
		custom.login_rpx();
	}
	if ($('#lightbox .lightbox_reset_password').length) {
		custom.reset_password();
	}
	
	// New topic subscribers
	$('input[type="checkbox"].select_all').live('change', function () {
		if ($(this).attr('checked')) {
			$('input[type="checkbox"][name="' + $(this).val() + '[]"]').attr('checked','checked');
		} else {
			$('input[type="checkbox"][name="' + $(this).val() + '[]"]').attr('checked','');
		}
	});
	$('input[type="checkbox"][name$="[]"]:unchecked').live('change', function () {
		name = $(this).attr('name');
		$('input[type="checkbox"][value="' + name.substr(0,(name.length - 2)) + '"].select_all').attr('checked','');
	});
	
	// Comment replies
	$('a[href^="#reply"]').live('click', function () {
		$('#reply-' + $(this).attr('rel')).parent().toggle(400);
		return false;
	});
	
	// Attach files to comment
	$('.comment form div.attach').hide();
	$('a[href^="#attach"]').live('click', function () {
		// alert('toggle');
		$(this).closest('form').find('div.attach').toggle(200);
		return false;
	});
	
	// Party Buzz size changer
	if($('div.module_partyBuzz').length){
		var resizeTimer = null;
		var obj = custom;
		$(window).bind('resize', function() {
			if (resizeTimer) clearTimeout(resizeTimer);
			resizeTimer = setTimeout(function(){ obj.resizePartyBuzz.apply(obj); }, 50);
		});
		custom.resizePartyBuzz();
	}
	
	
	// Edit VCARD
	if ($('form#vcard').length) {
		$('form#vcard a[href$="#cancel"]').addClass('disabled').hide();
		$('form#vcard a[href$="#submit"]').addClass('disabled').hide();
		$('form#vcard .confirm_password').hide();
		$('form#vcard input[name="password"]').bind('keyup change', function () {
			if ($(this).val()) {
				$('form#vcard .confirm_password').slideDown(200);
			} else {
				$('form#vcard .confirm_password').slideUp(200).val('');
			}
		});
		new Ajax_upload('.vcard a[href$="#upload_photo"] span', {
			action: '/user/update',
			name: 'photo_file[]',
			data: {
				user_key : $('.vcard a[href$="#upload_photo"]').attr('id')
			},
			onSubmit: function(file, extension) {
				if (! (extension && (/^(jpg|png|jpeg|gif)$/).test(extension))){
					// extension is not allowed
					alert('Error: you can only upload JPG, PNG or GIF images.');
					// cancel upload
					return false;
				}
				$('.vcard a[href$="#upload_photo"] span').html('Uploading…').closest('a').addClass('disabled');
			},
			onComplete: function(file, response) {
				params = eval("(" + response + ")");
				if (params.status == 'success') {
					$('.photo_file .photo').attr('src', '/file/' + file + '?width=220');
				} else {
					alert('There was an eror updating your profile photo.');
				}
				$('.vcard a[href$="#upload_photo"] span').html('Upload new photo').closest('a').removeClass('disabled');
			}
		});
		$('form#vcard a[href$="#edit"]').live('click', function () {
			if (!$(this).hasClass('disabled')) {
				$(this).addClass('disabled').hide();
				$('form#vcard a[href$="#cancel"], form#vcard a[href$="#submit"]').removeClass('disabled').show();
				$('form#vcard :disabled:not(option)').enable();
				$('form#vcard input[name="birthday"]').birthdayPicker();
				return false;
			}
		});
		$('form#vcard a[href$="#cancel"]').live('click', function () {
			if (!$(this).hasClass('disabled')) {
				$(this).addClass('disabled').hide();
				$('form#vcard').resetForm();
				$('form#vcard .error').removeClass('error');
				$('form#vcard a[href$="#edit"]').removeClass('disabled').show();
				$('form#vcard a[href$="#submit"]').addClass('disabled').hide();
				$('form#vcard input:enabled, form#vcard select:enabled,form#vcard textarea:enabled').attr('disabled','disabled');
				$('form#vcard .confirm_password').slideUp(200);
				return false;
			}
		});
		$('form#vcard').validate({
			debug: false,
			rules: {
				email: {
					email: true,
					required: true
				},
				birthday: {
					required: true,
					dateISO: true
				},
				confirm_password: {
					equalTo: "#password"
				}
			},
			errorPlacement: function(error, element) {
				// Don't place it anywhere
			},
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('form#vcard a[href$="#edit"]').removeClass('disabled').show();
						$('form#vcard a[href$="#cancel"], form#vcard a[href$="#submit"]').addClass('disabled').hide();
						$('form#vcard :enabled').attr('disabled','disabled');
						$('form#vcard .confirm_password').slideUp(200);
						$('form#vcard input[name="password"], form#vcard input[name="confirm_password"]').val('');
					}
				});
			}
		});
	}
	
	// Open external links in a new window (with confirmation)
	$('a[href^="http"]:not([href*="' + window.location.host + '"])').live('click', function () {
		if (confirm("Do you wish to navigate away from YourConspiracy.com?")) {
			window.open($(this).attr('href'));
		}
		return false;
	});
	
	// Tell clients to upgrade if they don't have access to a link
	$('#nav a:not([href])').click(function () {
		alert('This is not available with your current plan. Please contact support@yourconspiracy.com to upgrade your account.');
	});
	
	// User Subscriptions
	$('input:checkbox.subscribe').live('click', function () {
		if ($(this).attr('checked')) {
			$.getJSON('/user/subscribe', {record_key: $(this).val()}, function (data, textStatus) {
				if (textStatus == 'success' && data.status == 'success') {
					alert(data.message);
					return true;
				} else {
					alert(data.message);
					return false;
				}
			});
		} else {
			$.getJSON('/user/unsubscribe', {record_key: $(this).val()}, function (data, textStatus) {
				if (textStatus == 'success' && data.status == 'success') {
					alert(data.message);
					return true;
				} else {
					alert(data.message);
					return false;
				}
			});
		}
	});
	
	// Polls
	$('.module_poll input[type="radio"]').live('change', function () {
		//alert($(this).closest('.module_poll').html());
		$(this).closest('form').ajaxSubmit({
			dataType: 'json',
			success:  function(data) {
				//alert(data.message);
				if (data.status == 'success') {
					//alert('<img src="'+ data.result.chart_src +'" alt="" />');
					$('#poll-' + data.result.id + ' form').html('<img src="'+ data.result.chart_src +'&chs=160x80" alt="" />');
				} else if (data.status == 'error') {
					alert(data.message);
				}
			}
		});
		$(this).closest('.module_poll').find('input[type="radio"]').attr('disabled','disabled');
	});
	
	$('ul.attachments li a.image').lightBox({
		imageLoading: '/assets/img/ajaxload.gif',
		imageBlank: '/assets/img/x.gif',
		imageBtnPrev: '/assets/img/lightbox-btn-prev.gif',
		imageBtnNext: '/assets/img/lightbox-btn-next.gif',
		imageBtnClose: '/assets/img/lightbox-btn-close.gif'
	});
	
});

custom = {};

custom.login = function() {
	
	if ($('#lightbox .close').length) {
		$('#lightbox').live('click', function (e) {
			if (e.target.id == this.id || e.target.className == 'close') {
				$('#lightbox').hide();
				return false;
			}
		});
	}
	$('#login input[title]').inputHint();
	//$('#login a[href$="#forgot_password"]').hide();
	
	//$('#login input[name="email"]:first').focus();
	
	// Hide registration form
	$('#login .register').hide();
	
	$('#login').validate({
		debug: false,
		ignore: '.ignore',
		rules: {
			email: {
				required: true,
				email: true
			},
			birthday: {
				required: true,
				dateISO: true
			},
			password: 'required'
		},
		errorPlacement: function(error, element) {
			// Don't place it anywhere
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				success: function(data) {
					if (data && (data.substr(0,1) != '<')) {
						params = eval("(" + data + ")");
						if (params.error == 'password') {
							//$('#login a[href$="#forgot_password"]').removeClass('disabled').show();
							$('#login input:password:first').addClass('error');
						}
						$('#login_response').addClass('error').html(params.message);
					}
					else location = data.match(/url=(.*)"/i)[1];
				}
			});
		}
	});
	
	$('#login input[name="email"]:first').bind('keyup change', function (e) {
		if ($(this).val().match(/[\w]+@[\w]+\.[\w]+/)) {
			$(this).delay((e.type == 'change' ? 0 : 1500), function () {
				$.get('/user/check_email', {email: $('#login input[name="email"]:first').val()}, function (data) {
					if (data != 'true') {
						$('#login .register input, #login .register select').addClass('required').removeClass('ignore');
						//$('#login input[title]').inputHint();
						$('#login input[name="birthday"]').birthdayPicker();
						$('#login a[href$="#submit"] span').html('Register');
						$('#login input[name="action"]').val('register');
						$('#login .register').slideDown(400);
						//$('#login input[type="password"]:first').addClass('required').focus();
					} else {
						$('#login .register input, #login .register select').removeClass('required').addClass('ignore');
						$('#login a[href$="#submit"] span').html('Login');
						$('#login input[name="action"]').val('login');
						$('#login .register').slideUp(400);
					}
				});
			});
		} else if (!$(this).val()) {
			$('#login .register input, #login .register select').removeClass('required');
			$('#login a[href$="#submit"] span').html('Login');
			$('#login input[name="action"]').val('login');
			$('#login .register').slideUp(400);
		}
	});
};

custom.login_rpx = function() {
	
	$('#lightbox').live('click', function (e) {
		if (e.target.id == this.id || e.target.className == 'close') $('#lightbox').fadeOut(400);
		return false;
	});
	$('#lightbox input[title]').inputHint();
	
	// Hide registration form
	$('#login .merge').hide();
	
	$('#login input[name="birthday"]').birthdayPicker();
	
	$('#login').validate({
		debug: false,
		ignore: '.ignore',
		rules: {
			email: {
				required: true,
				email: true
			},
			birthday: {
				required: true,
				dateISO: true
			}
		},
		errorPlacement: function(error, element) {
			// Don't place it anywhere
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				success: function(data) {
					if (data && (data.substr(0,1) != '<')) {
						$('#login_response').html(data);
						//$('#login_response').html('<p class="help error">Password incorrect. <a href="#">Forgot password?</a></p>');
					}
					else location = data.match(/url=(.*)"/i)[1];
				}
			});
		}
	});
	
	custom.toggleLogin();
	
	$('#login input[name="email"]:first').bind('keyup change', function (e) {
		if ($(this).val().match(/[\w]+@[\w]+\.[\w]+/)) {
			$(this).delay((e.type == 'change' ? 0 : 1500), custom.toggleLogin);
		}
	});
};

custom.reset_password = function() {
	//alert('reset!');
	$('#lightbox').live('click', function (e) {
		if (e.target.id == this.id || e.target.className == 'close') $('#lightbox').fadeOut(400);
		return false;
	});
	//$('#login input[title]').inputHint();
	
	$('#login').validate({
		debug: false,
		ignore: '.ignore',
		rules: {
			password: 'required',
			confirm_password: {
				equalTo: '#password'
			}
		},
		errorPlacement: function(error, element) {
			// Don't place it anywhere
		},
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				success: function(data) {
					if (data && (data.substr(0,1) != '<')) {
						params = eval("(" + data + ")");
						$('#login_response').addClass('error').html(params.message);
					}
					else location = data.match(/url=(.*)"/i)[1];
				}
			});
		}
	});
	
};

custom.toggleLogin = function () {
	$.get('/user/check_email', {email: $('#login input[name="email"]').val()}, function (data) {
		if (data != 'true') {
			$('#login input:not(:hidden), #login select').addClass('required');
			$('#login input[type="password"]').removeClass('required');
			//$('#login input[title]').inputHint();
			$('#login input[type="submit"]').val('Register');
			$('#login input[name="action"]').val('register');
			$('#login .register').slideDown(400);
			$('#login .merge').slideUp(400);
		} else {
			$('#login input, #login select').removeClass('required');
			$('#login input[type="submit"]').val('Associate ' + $('#login input[name="providerName"]').val() + ' Profile');
			$('#login input[name="action"]').val('merge');
			$('#login .register').slideUp(400);
			$('#login .merge').slideDown(400);
			$('#login input[type="password"]').addClass('required').focus();
		}
	});
};

custom.resizePartyBuzz = function() {
	var buzz_container = $('div.module_partyBuzz');
	var newHeight = $(window).height() - $('#footer').height() - 16 - buzz_container.offset().top - 10;//numbers are padding
	newHeight = Math.max(newHeight,488);
	buzz_container.height(newHeight);
};

custom.validateForms = function() {
	$('form').validate({
		debug: true,
		ignore: '.ignore',
		rules: {
			email: {
				email: true,
				required: true
			},
			birthday: {
				required: true,
				dateISO: true
			},
			password: 'required',
			title: 'required',
			content: 'required',
			confirm_password: {
				equalTo: "#password"
			}
		},
		errorPlacement: function(error, element) {
			// Don't place it anywhere
		}
	});
};

jQuery.fn.maxLength = function() {
	if (maxlength = $(this).attr('maxlength')) {
		$(this).keyup(function () {
			target = $(this).parent().find('.count');
			count = maxlength - this.value.length;
			text = ' characters left';
			if (Math.abs(count) == 1) text = ' character left';
			if (count < 0) {
				$(target).addClass('warning').text(count + text);
			} else {
				$(target).removeClass('warning').text(count + text);
			}
		});
	}
};

jQuery.fn.birthdayPicker = function() {
	$(this).datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '1900:2100',
		minDate: '-100y',
		maxDate: '-13y',
		defaultDate: '-18y',
		dateFormat: 'yy-mm-dd',
		//dateFormat: 'dd/mm/yy  (d MM)',
		//altField: '#birthday',
		//altFormat: 'yy-mm-dd',
		onClose: function(date) {
			$(this).removeClass('hint');
		}
	});
	/*$(this).bind('change keyup', function () {
		if (bday = /([\d]{2})\/([\d]{2})\/([\d]{4})/.exec($(this).val())) {
			$('#birthday').val(bday[3]+'-'+bday[2]+'-'+bday[1]);
		} else {
			$('#birthday').val('');
		}
	});*/
};

jQuery.fn.delay = function(time,func){
	return this.each(function(){
		setTimeout(func,time);
	});
};

function buzzLogin()
{
	$.get("/session/login", {lightbox:true}, function (data) {
		$('#lightbox').html(data).fadeIn(400);
		custom.login();
	});	
}

