/* Enjin.com v5 Core JS */

$(document).ready(function(){
	$('.info_popup.login a.forgot, .info_popup.login .backtologin').click(function(){$('.info_popup.login .loginform').toggle(); $('.info_popup.login .forgotform').toggle(); return false;});
	$(".ghost_text").ghostText();
	
	if(location.hash == '#showlogin') $('nav.top .link.login').click();
	
	// links that open popup window
	$('a.new_window').click(Core.newWindow);

	// binds for input validation
	$('.info_popup.resetpassword .input input[type=password]').bindWithDelay("keydown blur", { input: $('.info_popup.resetpassword .input input[name=password]'), input2: $('.info_popup.resetpassword .input input[name=retype-password]') }, Core.validateResetPassword, 350);
	$('.info_popup.signup_website .input input[name=name]').bindWithDelay("keydown blur", { input: $('.info_popup.signup_website .input input[name=name]') }, Core.validateWebsiteName, 350);
	$('.info_popup.signup_website .input input[name=subdomain]').bindWithDelay("keydown blur", { input: $('.info_popup.signup_website .input input[name=subdomain]') }, Core.validateSubdomain, 350);
});

Core = { signedUp: false };

/*
 * Login popup
 */
Core.showLogin = function() {
	$('.info_popup').hide();
	$('.info_popup.login .loginform').show();
	$('.info_popup.login .forgotform').hide();
	$('.info_popup.login').fadeIn(180);
	$('.info_popup.login input[name=username]').focus();
}
Core.hideLogin = function() {
	$('.info_popup.login').fadeOut(180);
}

Core.login = function( action ) 
{
	$.post("/ajaxsite.php?s=auth",
		   { cmd: (typeof action === "undefined" ? "login" : action), username: $('.info_popup.login .loginform input[name=username]').val(), password: $('.info_popup.login .loginform input[name=password]').val(), remember: true },
		   function(data) {
				if ( data == 'success' ) {
					location.reload(true);
				}	
				else {
					$('.info_popup.login .loginform input').removeClass('error-input');
					if(data.inputs != undefined) for(x in data.inputs) { $('.info_popup.login .loginform input[name='+data.inputs[x]+']').addClass('error-input'); }

					if ( data.error != "You must <a href='\/signup\/verifyemail'>verify your account<\/a> before logging in." ) $('.info_popup.login .loginform .login-error').html(data.error).hide().fadeIn(150);
					else {
						$('.info_popup.login .loginform .login-error').html('Your account is not active. <a href="javascript:Core.resendAccountInactive();">Click here</a> to resend your email confirmation.').hide().fadeIn(150);
					}
				}
			},
			'json');
}

Core.forgotPassword = function() {
	$.post("/ajaxsite.php?s=auth", { cmd: "forgot-password", email: $('.info_popup.login .forgotform input[name=email]').val() }, function(data){
		if(data == 'success') {
			$('.info_popup.login .forgotform').hide();
			$('.info_popup.login .forgot-success .forgot-email-sent').html($('.info_popup.login .forgotform input[name=email]').val());
			$('.info_popup.login .forgot-success').show();
		}
		else $('.info_popup.login .forgotform .forgot-error').html(data.error).hide().fadeIn(150);
	}, 'json');
}

Core.resendAccountInactive = function() {
	var postData = { cmd: "resend-email", email: $('.info_popup.login .loginform input[name=username]').val() };
	$.post("/ajaxsite.php?s=signup", postData, function(data){
		if(data.success != undefined) {
			$('.info_popup.login .loginform .error.login-error').html('').hide();
			Core.hideLogin();
			Core.showVerifyEmail($('.info_popup.login .loginform input[name=username]').val());
		}
		else {
			$('.info_popup.login .loginform .error.login-error').html('There was an error sending your confirmation email. Please create a new account or <a href="/about/contact">contact support</a>.').show();
		}
	}, 'json');
}


/*
 * Signup popup
 */
Core.showSignup = function() {
	if(!Core.signedUp) {
		if(!signup_initiated) {
			var signup_initiated = true;

			$('.info_popup.signup .input input[name=username]').bindWithDelay("keydown blur", { input: $('.info_popup.signup .input input[name=username]') }, Core.validateUsername, 50);
			$('.info_popup.signup .input input[name=email]').bindWithDelay("keydown blur", { input: $('.info_popup.signup .input input[name=email]') }, Core.validateEmail, 750);
			$('.info_popup.signup .input input[name=password]').bindWithDelay("keydown blur", { input: $('.info_popup.signup .input input[name=password]') }, Core.validatePassword, 350);
			$('.info_popup.changeemail .input input[name=email]').bindWithDelay("keydown blur", { input: $('.info_popup.changeemail .input input[name=email]') }, Core.validateEmail, 750);
		}

		$('.info_popup').hide();
		$('.info_popup.signup').fadeIn(180);
		$('.info_popup.signup .input input[name=username]').focus();
	}
	else {
		Core.showVerifyEmail();
	}
}

Core.hideWindow = function(el) {
	$(el).closest('.info_popup').fadeOut(180);
}

Core.hideWindows = function() {
	$('.info_popup').fadeOut(180);
}

Core.validateUsername = function(e) {
	$(e.data.input).parent().siblings('.result').removeClass('ok');

	if($(e.data.input).removeClass('error-input').val().length > 0) $(e.data.input).parent().siblings('.result').addClass('ok').text('');
	else $(e.data.input).addClass('error-input').parent().siblings('.result').text('Please enter a username');
}

Core.validateWebsiteName = function(e) {
	$(e.data.input).parent().siblings('.result').removeClass('ok');

	if($(e.data.input).removeClass('error-input').val().length > 0) $(e.data.input).parent().siblings('.result').addClass('ok').text('');
	else $(e.data.input).addClass('error-input').parent().siblings('.result').text('Please enter a name for your website');
}

Core.validateEmail = function(e) {
	$.post("/ajaxsite.php?s=signup", { cmd: "verify-email", email: $(e.data.input).val() }, function(data){
		$(e.data.input).parent().siblings('.result').removeClass('ok');
		if(data == 'success') {
			$(e.data.input).parent().siblings('.result').addClass('ok').text('');
			$(e.data.input).removeClass('error-input');
		}
		else {
			$(e.data.input).parent().siblings('.result').text(data.error);
			$(e.data.input).addClass('error-input');
		}
	}, 'json');
}

Core.validatePassword = function(e) {
	$(e.data.input).parent().siblings('.result').removeClass('ok');

	if($(e.data.input).removeClass('error-input').val().length >= 6 && $(e.data.input).val().length <= 24) $(e.data.input).parent().siblings('.result').addClass('ok').text('');
	else $(e.data.input).addClass('error-input').parent().siblings('.result').text('Password must be 6-24 characters');
}

Core.validateResetPassword = function(e) {
	$(e.data.input).parent().siblings('.result').removeClass('ok');
	$(e.data.input2).parent().siblings('.result').removeClass('ok');

	if($(e.data.input).removeClass('error-input').val().length >= 6 && $(e.data.input).val().length <= 24) $(e.data.input).parent().siblings('.result').addClass('ok').text('');
	else $(e.data.input).addClass('error-input').parent().siblings('.result').text('Password must be 6-24 characters');

	if($(e.data.input2).removeClass('error-input').val().length > 0 && $(e.data.input2).val() == $(e.data.input).val()) $(e.data.input2).parent().siblings('.result').addClass('ok').text('');
	else if($(e.data.input2).val().length == 0) $(e.data.input2).parent().siblings('.result').removeClass('ok').text('');
	else $(e.data.input2).addClass('error-input').parent().siblings('.result').text('The passwords must match');
}

Core.submitSignup = function() {
	if(!$('.info_popup.signup .input input[name=username]').parent().siblings('.result').hasClass('ok')) $('.info_popup.signup .input input[name=username]').focus();
	else if(!$('.info_popup.signup .input input[name=email]').parent().siblings('.result').hasClass('ok')) $('.info_popup.signup .input input[name=email]').focus();
	else if(!$('.info_popup.signup .input input[name=password]').parent().siblings('.result').hasClass('ok')) $('.info_popup.signup .input input[name=password]').focus();
	else {
		Core.submitCaptcha = function() {
			Core.signup();
		};
		$('.info_popup').hide();
		Core.popupCaptcha();
	}
}

Core.popupCaptcha = function(error) {
	if(error) $('#recaptcha_response_field').addClass('error-input');
	else $('#recaptcha_response_field').removeClass('error-input');

	$('.info_popup.captcha').show();

	Recaptcha.create(Core.recaptcha_publickey,
		"signup_recaptcha",
		{theme: "custom", custom_theme_widget: "signup_recaptcha", callback: Recaptcha.focus_response_field}
	);
}

Core.signup = function( action )
{
	var recaptcha_challenge = Recaptcha.get_challenge();
	var recaptcha_response = Recaptcha.get_response();

	$.post("/ajaxsite.php?s=signup",
	   { cmd: (typeof action === "undefined" ? "signup" : action), username: $('.info_popup.signup .signupform input[name=username]').val(), email: $('.info_popup.signup .signupform input[name=email]').val(), password: $('.info_popup.signup .signupform input[name=password]').val(), recaptcha_challenge: recaptcha_challenge, recaptcha_response: recaptcha_response },
	   function(data) {
			if ( data.success != undefined ) {
				Core.signedUp = true;
				Core.showVerifyEmail();
			}
			else {
				if(data.error == 'captcha') {
					Recaptcha.reload();
					$('#recaptcha_response_field').addClass('error-input');
					$('#recaptcha_response_field').val('');
				}
				else {
					Recaptcha.reload();
					$('#recaptcha_response_field').removeClass('error-input');
					$('#recaptcha_response_field').val('');

					Core.showSignup();
					$('.info_popup.signup .signupform input').removeClass('error-input');

					if ( data.error ) $('.info_popup.signup .error').html(data.error).hide().fadeIn(150);
					else $('.info_popup.signup .error').html('There was an error. Please try again or contact support.').hide().fadeIn(150);
				}
			}
		},
		'json');
}

Core.showVerifyEmail = function(email) {
	$('.info_popup').hide();
	if(email != undefined) $('.info_popup.verifyemail p strong.address').text(email);
	else $('.info_popup.verifyemail p strong.address').text($('.info_popup.signup .input input[name=email]').val());
	$('.info_popup.verifyemail').show();
}

Core.resendEmail = function(link, recaptcha_challenge, recaptcha_response) {
	$('.info_popup.verifyemail .resend-link').css('visibility', 'hidden').fadeOut(650, function(){$(this).css('visibility', 'visible').fadeIn(500)});

	var postData = { cmd: "resend-email" };
	if(recaptcha_challenge != undefined) postData['recaptcha_challenge'] = recaptcha_challenge;
	if(recaptcha_response != undefined) postData['recaptcha_response'] = recaptcha_response;

	$.post("/ajaxsite.php?s=signup", postData, function(data){
		if(data.success != undefined) {
			$('.info_popup.verifyemail p.sent-email, .info_popup.verifyemail h1.sent-title').hide();
			$('.info_popup.verifyemail p.resent-email, .info_popup.verifyemail h1.resent-title').show();
		}
		else {
			Core.submitCaptcha = function() {
				Core.resendEmailCaptcha();
			};
			if(recaptcha_challenge != undefined) var cError = true;
			else var cError = false;
			Core.popupCaptcha(cError);
		}
	}, 'json');
}

Core.resendEmailCaptcha = function() {
	var recaptcha_challenge = Recaptcha.get_challenge();
	var recaptcha_response = Recaptcha.get_response();

	$.post("/ajaxsite.php?s=signup",
	   { cmd: 'resend-email', recaptcha_challenge: recaptcha_challenge, recaptcha_response: recaptcha_response },
	   function(data) {
			if (data.success != undefined) {
				$('.info_popup.captcha').hide();
			}
			else {
				Recaptcha.reload();
				$('#recaptcha_response_field').removeClass('error-input');
				$('#recaptcha_response_field').val('');
			}
		},
		'json');
}

Core.showChangeEmail = function() {
	$('.info_popup.changeemail').show();
	$('.info_popup.changeemail input[name=email]').focus();
}

Core.submitChangeEmail = function() {
	if(!$('.info_popup.changeemail input[name=email]').parent().siblings('.result').hasClass('ok')) {
		$('.info_popup.changeemail input[name=email]').addClass('error-input').focus();
	}
	else {
		Core.disableButton($('.info_popup.changeemail input[type=submit]'), 1);
		var postData = { cmd: "change-email", email: $('.info_popup.changeemail input[name=email]').val() };

		$.post("/ajaxsite.php?s=signup", postData, function(data){
			if(data == 'success') {
				$('.info_popup.changeemail').fadeOut(180);
				$('.info_popup.verifyemail p strong.address').text($('.info_popup.changeemail .input input[name=email]').val());
			}
			else {
				if(!data.error) data.error = 'There was an error, please try again.'.
				$('.info_popup.changeemail .error').text(data.error);
			}
		}, 'json');
	}
}

Core.submitResetPassword = function() {
	if(!$('.info_popup.resetpassword input[name=password]').parent().siblings('.result').hasClass('ok')
	|| !$('.info_popup.resetpassword input[name=retype-password]').parent().siblings('.result').hasClass('ok')) {
		//
	}
	else {
		Core.disableButton($('.info_popup.resetpassword input[type=submit]'), 1);
		var postData = { cmd: "reset-password", password: $('.info_popup.resetpassword input[name=password]').val(), confirmpassword: $('.info_popup.resetpassword input[name=retype-password]').val() };

		$.post("/ajaxsite.php?s=auth", postData, function(data){
			if(data == 'success') {
				//$('.info_popup.resetpassword').fadeOut(180);
				$('nav.top .link.login').click();
			}
			else {
				if(!data.error) data.error = 'There was an error, please try again.';
				$('.info_popup.resetpassword .error').show().text(data.error);
			}
		}, 'json');
	}
}



Core.newWindow = function(evt, w) {
  var e = evt.target;
  if (e.tagName != "A") e = getParentByTag(e,"A");
  if (!e) return;
  
  var width = 500;
  var height = 640;
  
  if($(e).attr('w') > 0) width = $(e).attr('w');
  
  // offset slightly from current window
  var screenX = (window.screenX ? window.screenX : window.screenLeft) + 40;
  var screenY = (window.screenY ? window.screenY : window.screenTop - 80) + 40;
  
  var w = window.open(e.href,e.target,"status,scrollbars,resizable,titlebar,left="+screenX+",top="+screenY+",width="+width+",height="+height);

  evt.preventDefault();
  evt.stopPropagation();

  w.focus();
}


/*
 * Gift code popup
 */
Core.applyGiftcode = function(code) {
	$.getJSON("/ajaxsite.php?s=giftcode&cmd=apply", { giftcode: code }, function(data){
		if(data.error != undefined) $('.info_popup.giftcode .error').html(data.error);
		else window.location = '/';
	});
}
Core.hideGiftcode = function() {
	$.getJSON("/ajaxsite.php?s=giftcode&cmd=hide", {}, function(data){
		if(data.error != undefined) $('.info_popup.giftcode .error').html(data.error);
		else window.location = '/';
	});
}
Core.signupGiftcode = function() {
	$.getJSON("/ajaxsite.php?s=giftcode&cmd=hide", {}, function(data){
		window.location = '/signup';
	});
}

/*
 * Like Site
 */
Core.enjinLikeSite = function(el, site_id) {
	var likes = $(el).siblings('.likes').children('span');

	if($(el).parent().hasClass('liked')) {
		$(el).parent().removeClass('liked');
		var cmd = 'unlike-site';
		likes.text(parseInt(likes.text(), 10)-1);
	}
	else {
		$(el).parent().addClass('liked');
		var cmd = 'like-site';
		likes.text(parseInt(likes.text(), 10)+1);
	}
	$.post('/ajax.php?s=site', {cmd: cmd, site_id: site_id});
}


Core.disableButton = function(input, seconds, disabledText) {
	if(disabledText != undefined) {
		var origText = $(input).val();
		$(input).val(disabledText);
	}

	function reenableButton()
	{
		$(input).removeAttr('disabled');
		$(input).removeClass('disabled');
		if(disabledText != undefined) $(input).val(origText);
	}

	$(input).attr('disabled', true);
	$(input).addClass('disabled');
	setTimeout(reenableButton, seconds*1000);
}


/*
 * jQuery Plugins
 */

$.fn.ghostText = function() {
	return this.each(function() {
		var text = $(this).attr("data-placeholder");
		if (text != "") {
			if ($(this).val() == "") $(this).val(text);
			$(this).focus(function() {
				if ($(this).val() == text) {
					$(this).val("");
					$(this).removeClass('ghosted');
				}
			});
			$(this).blur(function() {
				if ($(this).val() == "") {
					$(this).val(text);
					$(this).removeClass('ghosted');
				}
			});
		}
	});
};


/*
bindWithDelay jQuery plugin
Author: Brian Grinstead
MIT license: http://www.opensource.org/licenses/mit-license.php

http://github.com/bgrins/bindWithDelay
http://briangrinstead.com/files/bindWithDelay

Usage:
	See http://api.jquery.com/bind/
	.bindWithDelay( eventType, [ eventData ], handler(eventObject), timeout, throttle )

Examples:
	$("#foo").bindWithDelay("click", function(e) { }, 100);
	$(window).bindWithDelay("resize", { optional: "eventData" }, callback, 1000);
	$(window).bindWithDelay("resize", callback, 1000, true);
*/

(function($) {
$.fn.bindWithDelay = function( type, data, fn, timeout, throttle ) {
	var wait = null;
	var that = this;

	if ( $.isFunction( data ) ) {
		throttle = timeout;
		timeout = fn;
		fn = data;
		data = undefined;
	}

	function cb() {
		var e = $.extend(true, { }, arguments[0]);
		var throttler = function() {
			wait = null;
			fn.apply(that, [e]);
		};

		if (!throttle) { clearTimeout(wait); }
		if (!throttle || !wait) { wait = setTimeout(throttler, timeout); }
	}

	return this.bind(type, data, cb);
}
})(jQuery);
