// Site-wide JavaScript 

var subtexts = ['v6', 'what ever happened to them', 'sharkie, come back!', 'est. 2003', 'we run newgrounds\' underground sewer system', '<a href="http://www.newgrounds.com/portal/view/537299">have you watched ELO - Twilight?</a>', '...', 'make flash', 'HA HA HA GOOD ONE WINE LOCK', 'where the fun never stops and the work never starts', 'two backgrounds!?', 'fellow candles, rebel!', 'щ(ﾟДﾟщ)', 'it\'s dangerous to go alone, take this', 'herp derp', 'SHARKS AREN\'T BALLS', 'so who\'s this peter fucker?', 'the clock crew\'s retarded little brother', 'fork. the end', 'formerly the lock crew', 'barely breathing', 'frites, camembert, baguette et escargots', 'balls to the wall', 'secret underground society of animators', ':gimpy:', 'cruise control for cool', 'abandon all hope ye who enter here', 'flash?' , 'everytime you make a flash, an angel gets his wings', 'what\'s a samegame?', 'beware the snuggie', 'the game', 'got flash? no? oh okay then', 'anonymous is legion; so are we', '( . )Y( . )', 'et tu, peach?', 'remember the fallen', 'in the beginning, there was glorton...', 'quickly, use my body for warmth', 'post your cunt if you\'re serious', 'v92481953', 'have you seen our good stuff? no? oh...', 'quick, look busy', 'they were lock legion', 'om nom nom nom', 'cocked, locked, and ready to rock', '.org', 'now with 30% less userbase', 'we\'re just as good, trust us', 'addicted to minecrack', 'rock out with your lock out', 'four score and seven sites ago', 'everyday superheroes', 'expect no mercy', 'origami plz draw me i posted days ago!!', 'we have seen the future. it is glorious', 'hey where\'s my award', '<3', 'inventor of AIDS', 'let me tell you about my boner', 'PERSON OF AFRICAN AMERICAN HERITAGE', '<em>LEGALLY ACQUIRE</em>', 'lolk', 'wait, are you sarcastic or . . . ?', 'hi doorknob', '<span style="color: #0F0;">N</span>', 'clock crew is ghey lololol', 'welcum', 'we\'re p. cool', 'hey there sexy ;)', 'don\'t leave :c', '<a href="http://www.locklegion.org/submit/">hey, you think this is easy?</a>', '<a href="http://www.newgrounds.com/portal/view/560214">have you watched Dancing in the Moonlight?</a>', 'remember the time we made that music collab?', 'best thing since your mom', 'not your average clock crew', 'we eat lightning', 'wtd?', 'are we locks? or are we dancers?', 'hey, let\'s count to five', 'THERE IS NO RESISTING THE COPPER THEME', 'normal is boring', 'we don\'t need noses to smell you\'re impressed', '(☝ﾟ∀ﾟ)☝', 'the clock crew hates us!?!?!?', 'oh boy oh boy', 'GODDAMIT NINTENDO', 'forging talented animators', 'made a pie', 'be willsmithlock', '<a onclick="openFlash(\'http://uploads.ungrounded.net/570000/570846_Rockbattle.swf', 'RockBattle:Wine VS MP3 by JacoLock\', 720, 480);">have you watched RockBattle: Wine VS MP3?</a>', 'fade in . . . fade out', 'it makes your lock bigger', 'legally acquired', 'UNCOUTH AS FUCK', 'where T&A stands for Tweens and Actionscript', 'a train wreck in progress', 'we just won\'t die', 'fight me', 'kk', 'last night i swallowed the moon', 'we don\'t care if it\'s your birthday'];

$(document).ready(function(){
	
	var coin = getRandomInt(0, 1);
	if (coin)
		$('body').css('backgroundImage', 'url(http://files.myfrogbag.com/dmv6c0/LL2.gif)');
		
    setInterval(switchSubtext, 5000);
    
	$('input.numeric').forceNumeric();
	
	$('.box .textfield').focus(function () {
        $(this).css('backgroundColor', '#364B5E');
    });
    
    $('.box .textfield').blur(function () {
        $(this).css('backgroundColor', '#24323E');
    });
		
	$('#login .textfield').focus(function () {
        $(this).css('backgroundColor', '#8B7165');
    });
    
    $('#login .textfield').blur(function () {
        $(this).css('backgroundColor', '#6C584F');
    });
	
	$('.contain textarea').blur(function () {
        $(this).css('backgroundColor', '#FBFF62');
    });
	
	$('.contain textarea').focus(function () {
        $(this).css('backgroundColor', '#FCFF9A');
    });
	
	$('.contain .textfield').blur(function () {
        $(this).css('backgroundColor', '#FBFF62');
    });
	
	$('.contain .textfield').focus(function () {
        $(this).css('backgroundColor', '#FCFF9A');
    });

});

function switchSubtext() {
	$('#header h2').fadeOut('slow', function(){
		$('#header h2').html(subtexts[getRandomInt(0, subtexts.length)]);
	});
	$('#header h2').fadeIn('slow');
}

function validateRegistration()
{
	var regexUsername = new RegExp('^[A-Za-z0-9-]{3,20}$');
	var regexPassword = new RegExp('^[A-Za-z0-9-]{6,20}$');
	var regexEmail = new RegExp('^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$');
	
	var username = $('#username').val();
	var password = $('#password').val();
	var password2 = $('#password2').val();
	var email = $('#email').val();
	var question = $('#question').val();
	
	var response = $.ajax({
  		url: 'http://www.locklegion.org/ajax/available/',
  		cache: false,
		async: false,
		data: 'username=' + username,
	}).responseText;
		
	var errors = [];

	if (!username)
		errors.push('Please type in your username!');
	else if (!regexUsername.test($.trim(username)))
		errors.push('Username is not valid! Must be 3-20 characters in length and contain only alpha-numeric characters.');
	else if (response == 'un')
		errors.push('Username is not available!');
		
	if (!password)
		errors.push('Please type in your password!');
	else if (!regexPassword.test($.trim(password)))
		errors.push('Password is not valid! Must be 6-30 characters in length and contain only alpha-numeric characters.');
	else if (password != password2)
		errors.push('Your passwords don\'t match!');
	
	if (!email)
		errors.push('Please type in your e-mail!');
	else if (!regexEmail.test($.trim(email)))
		errors.push('E-mail is not valid!');
	
	if (!question)
		errors.push('How many letters are in \'locklegion\'?');
	else if (parseInt(question) != 10)
		errors.push('\'locklegion\' does not have ' + question + ' letters; what are you? some kind of idiot?');
				
	if (errors.length) {
		if (!$('#errors').length)
			$('<div class="box" id="errors">' + listErrors(errors)  + '</div>').insertAfter('#side');
		else
			$('#errors').html(listErrors(errors));
		return false;
	} else
		return true;
}

function validateTopic()
{
	var subject = $('#subject').val();
	var message = $('#message').val();
		
	var errors = [];

	if (!subject)
		errors.push('Your topic subject can\'t be blank!');
		
	if (!message)
		errors.push('Your topic can\'t be blank!');
					
	if (errors.length) {
		if (!$('#errors').length)
			('.head:first').before('<div class="head" id="errors">' + listErrors(errors)  + '</div>');
		else
			$('#errors').html(listErrors(errors));
		return false;
	} else
		return true;
}

function validatePost()
{
	var message = $('#message').val();
	if (!message) {
		alert('Your post can\'t be blank!');
		return false;
	} else
		return true;
}
	
(function ($) {
    $.fn.forceNumeric = function () {
        return this.each(function () {

            $(this).keyup(function() {
                if (!/^[0-9]+$/.test($(this).val())) {
                    $(this).val($(this).val().replace(/[^0-9]/g, ''));
                }
            });
        });
    };
})(jQuery);
 
function listErrors(errors) 
{
	var htmlStr = '<h2>Oops, you made a couple of misakes:</h2><ul>';
	for (var i = 0; i < errors.length; i ++) {
		htmlStr += '<li>' + errors[i] + '</li>';
	}
	return htmlStr + '</ul>';
}
  
function extendTextarea(textarea)
{
	$(textarea).animate({ height: '+=200', }, 500, function() {
		if (!$('#revert').length)
			$('#extend').after('<a id="revert" class="right btn" href="javascript:revertTextarea(\'#message\');">Revert Textarea</a>')
	});
}

function revertTextarea(textarea)
{
	$(textarea).animate({ height: '200px', }, function() {
		$('#revert').fadeOut('fast', function(){
			$('#revert').remove();
		});
  	});
}

function likePost(postId)
{
	var response = $.ajax({
  		url: 'http://www.locklegion.org/ajax/like.php',
  		cache: false,
		data: 'postId=' + postId,
	}).responseText;
	
	if (response == 'already')
		alert('Umm, you already liked this.');
	
	$('#like-' + postId).after('<a id="unlike-' + postId + '" class="btn" href="javascript:unlikePost(' + postId + ');">Unlike</a>')
	$('#like-' + postId).remove();
}

function unlikePost(postId)
{
	var response = $.ajax({
  		url: 'http://www.locklegion.org/ajax/unlike.php',
  		cache: false,
		data: 'postId=' + postId,
	}).responseText;
	
	if (response)
		alert(response);
		
	$('#unlike-' + postId).after('<a id="like-' + postId + '" class="btn" href="javascript:likePost(' + postId + ');">Like</a>')
	$('#unlike-' + postId).remove();
}

function quotePost(postId)
{
	var username = $('#post-' + postId + ' .username').text();
	var post = $('#quotable-' + postId).text();
	insertText('[quote=' + username + ']' + post, '[quote]', 'message');
}

function deletePost(postId)
{
	var response = confirm("Are you sure you want to delete this post? You can't get it back.");
	if (response)
	{
		var category = $('#category').val();
		var topic = $('#topic-id').val();
		$('#post-' + postId).fadeOut('slow', function(){
			$('#post-' + postId).remove();
		});
		var response = $.ajax({
		type: "POST",
  		url: 'http://www.locklegion.org/ajax/delete.php',
  		cache: false,
		data: 'postId=' + postId + '&category=' + category + '&topic=' + topic
		}).responseText;
		
		if (response)
			alert(response);
	}
}

function editPost(postId)
{
	$('#post-' + postId + ' .post-text').hide();
	$('#post-' + postId + ' .post-text').after('<textarea id="edit-box-' + postId + '" maxlength="8192">' + $('#quotable-' + postId).text() + '</textarea>');
	$('#edit-' + postId).replaceWith('<a id="save-' + postId + '" class="btn" href="javascript:savePost(' + postId + ');">Save</a>');
}

function savePost(postId)
{	
	$('#save-' + postId).replaceWith('<a class="btn">Saved!</a>')
	
	post = $('#edit-box-' + postId).val();
	$.ajax({
		type: "POST",
		url: 'http://www.locklegion.org/ajax/save.php',
		cache: false,
		data: 'post=' + post + '&postId=' + postId,
		success: function(data) {
    		$('#post-' + postId + ' .post-text').show();
			$('#post-' + postId + ' .post-text').html(data);
  		}
	});
	$('#edit-box-' + postId).remove();
}

function insertText(open, close, elementId)
{

	msgfield = document.getElementById(elementId);

	// IE support
	if (document.selection && document.selection.createRange)
	{
		msgfield.focus();
		sel = document.selection.createRange();
		sel.text = open + sel.text + close;
		msgfield.focus();
	}

	// Moz support
	else if (msgfield.selectionStart || msgfield.selectionStart == '0')
	{
		var startPos = msgfield.selectionStart;
		var endPos = msgfield.selectionEnd;

		msgfield.value = msgfield.value.substring(0, startPos) + open + msgfield.value.substring(startPos, endPos) + close + msgfield.value.substring(endPos, msgfield.value.length);
		msgfield.selectionStart = msgfield.selectionEnd = endPos + open.length + close.length;
		msgfield.focus();
	}

	// Fallback support for other browsers
	else
	{
		msgfield.value += open + close;
		msgfield.focus();
	}

	return;
}

function ask()
{
	var response = confirm("Are you sure you want to delete this topic? You can't get it back.");
	if (response)
		return true;
	return false;
}

function getRandom(min, max)
{
  return Math.random() * (max - min) + min;
}
 
function getRandomInt(min, max)
{
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function openFlash(url, title, w, h) {
	var x = (screen.width / 2) - (w / 2);
	var y = (screen.height / 2) - (h / 2);
	var settings = 'width = ' + w + ', height = ' + h + ', top = ' + y + ', left = ' + x + ', scrollbars = 0,location = 0, directories = 0, status = 0, menubar = 0, toolbar = 0, resizable = 0';
	
	window.open(url, title, settings);
}
