$(function() {

	var tzo=(new Date().getTimezoneOffset()/60)*(-1)

	// Show related inputs
	$("input.listen").keydown( function() {
		var itemToShow = $(this).attr("rel");
		$("#" + itemToShow).fadeIn("quick");
	});
	
	// hide search list
	$('#myGamesList').click( function() {
		$('#searchGameList').html();
		$('#yourGameList').show();
		return false;
	});
	
	// Setup
	$('input.hint').hint();
	$('textarea').hint();
	$('input#id_displayname').checkusername();
	$('input#id_username').checkemail();
	
	//$("input[@type='submit']").submitcheck();
	$('form#arrange #id_dob_day').empty()
	
	$('#userNav form select').change(function(){
	
		var str = "";
	
		$("select option:selected").each(function () {
			str += $(this).val();
		});
		
		$('#userNav form').attr("action", "/" + str + "/search/");
		
	}).change();

});

$.fn.hint = function() {
	return this.each(function(){
		var t = $(this); // get jQuery version of 'this'
		var title = t.attr('title'); // get it once since it won't change
		
		if (title) { // only apply logic if the element has the attribute
			
			// on focus, set value to blank if current value matches title attr
			t.focus(function(){
				if (t.val() == title) {
					t.val('');
					t.addClass('blur');
				}
			})

			// on blur, set value to title attr if text is blank
			t.blur(function(){
				if (t.val() == '') {
					t.val(title);
					t.removeClass('blur');
				}
			})

			// now change all inputs to title
			t.blur();
		}
	})
}

$.fn.checkusername = function() {
	return this.each(function(){

		var validateUsername = $('#registerDisplayName label em');
		var t = $(this); // get jQuery version of 'this'
		
		function validate () {
			
			var t = this; 
			
			if (this.value != this.lastValue && this.value.length > 1) {
			
				if (this.timer) clearTimeout(this.timer);
				validateUsername.removeClass('error').html('<img src="/static/v5/images/spinner.gif" height="16" width="16" class="vAlignMiddle" /> checking availability...');
				
				this.timer = setTimeout(function () {
				$.ajax({
					url: '/checkusername/?username=' + t.value,
					data: 'username=' + t.value,
					dataType: 'json',
					type: 'post',
					success: function (j) {
						validateUsername.html(j.msg);
						
						if(j.ok) {
						
							// check image isn't already there
							var count = $('img#id_displayname_tick').length;
							
							if(count <=0) {
								$('input#id_displayname').after(' <img src="/static/v5/images/icon/tick.png" height="16" width="16" id="id_displayname_tick" class="vAlignMiddle" />');
							}
						
						} else {
						
							$('img#id_displayname_tick').remove();
							
						}

					}
				});
				}, 200);
				
				this.lastValue = this.value;
			}
			
		}
		
		t.keyup(validate);
	
	})

}

$.fn.checkemail = function() {
	return this.each(function(){
	
		var validateEmail = $('#registerEmail label em');
		var t = $(this); // get jQuery version of 'this'
		
		function validate () {
		
			var t = this; 
			
			if (this.value != this.lastValue && this.value.length > 1) {
				if (this.timer) clearTimeout(this.timer);
				validateEmail.removeClass('error').html('<img src="/static/v5/images/spinner.gif" height="16" width="16" class="vAlignMiddle" /> checking availability...');
				
				this.timer = setTimeout(function () {
				$.ajax({
					url: '/checkemail/?username=' + t.value,
					data: 'username=' + t.value,
					dataType: 'json',
					type: 'post',
					success: function (j) {
						validateEmail.html(j.msg);
						
						if(j.ok) {
						
							// check image isn't already there
							var count = $('img#id_username_tick').length;
							
							if(count <=0) {
								$('input#id_username').after(' <img src="/static/v5/images/icon/tick.png" height="16" width="16" id="id_username_tick" class="vAlignMiddle" />');
							}
						
						} else {
						
							$('img#id_username_tick').remove();
							
						}
					}
				});
				}, 200);
				
				this.lastValue = this.value;
			}
			
		}
		
		t.keyup(validate);
	
	})

}

$.fn.checkvalue = function() {
	return this.each(function(){

		var t = $(this); // get jQuery version of 'this'
		
		function validate () {
			
			if (this.value != this.lastValue && this.value.length > 1) {
			
				console.log('sdfsdf');
			
				if (this.timer) clearTimeout(this.timer);
				
				this.timer = setTimeout(function () {

					// check image isn't already there
					var count = $('img', t.parent()).length;
					
					if(count <=0) {
						t.after(' <img src="/static/v5/images/icon/tick.png" height="16" width="16" class="vAlignMiddle" />')
					}
				
				}, 200);
				
				this.lastValue = this.value;
				
			} else if (this.value.length <= 0) {
				
				$('img', t.parent()).remove();
				
			}
			
		}
		
		t.keyup(validate);
	
	})

}

$.fn.getgames = function(page) {
	return this.each(function(){

		var action = 'add';
		var url = '';
		var contentSection = $('#searchGameList');
		var oldContentSection = $('#yourGameList');
		var t = $(this); // get jQuery version of 'this'
		
		function validate () {
		
			var t = this;
			
			if (t.value.length >= 3 && t.value != 'What game do you want to add?')
			{
			
				if (this.value != this.lastValue) {
					
					if (this.timer) clearTimeout(this.timer);
					
					//contentSection.html('<h2><span><img src="/static/images/ajax-loader.gif" height="16" width="16" /> One sec...</span></h2>');
					
					this.timer = setTimeout(function () {
					
					$.ajax({
						url: '/games/search/?game=' + t.value,
						data: 'username=' + t.value,
						dataType: 'json',
						type: 'post',
						success: function (j) {
						
						if (page == 'configure') {
							contentSection.html('<h2><span>Click on a game to add it - <a href="/configure/3/" class="showGames">Show games I\'ve added</a></span></h2> <ul class="textList"></ul>');
						} else {
							contentSection.html('<h2><span>Games called "' + t.value + '" - <a href="/settings/games/" class="showGames">Show mine again</a></span></h2> <ul class="textList"></ul>');
						}
						
						if (page == 'arrange') {
							action = 'new';
							url = '/games/'
						} else if (page == 'games') {
							action = '';
						} else if (page != 'configure') {
							url = '/games/'
						}
						
						for (i in j) {
							$('#searchGameList ul.textList').append('<li><span><em>' + j[i].platform + '</em></span> &ndash; <a href="' + url + '' + j[i].url_platform + '/' + j[i].id + '/' + j[i].url_game + '/' + action + '/" class="' +	action + 'Game" title="Add">' + j[i].title + '</a></li>');
						}
						
						oldContentSection.hide()
						
						$('div#searchGameList').show()
						$('a.addGame').quickAddRemove();
						
						},
						error: function (j) {
						
						contentSection.html('<h2 class="error"><span>We can\'t find that game, try using its full name.</span></h2>')
						oldContentSection.hide()
						
						}
						
					});
					}, 200);
					
					this.lastValue = this.value;
				}
			
			}
			
		}
		
		t.keyup(validate).blur(validate);
	
	})

}

$.fn.getEvents = function(page) {
	return this.each(function(){

		var t = $(this); // get jQuery version of 'this'

		$.ajax({
			url: '/events/',
			dataType: 'json',
			type: 'post',
			success: function (j) {
				// ?????????
			},
			error: function (j) {
				// ?????????
			}
		})
	})

}

$.fn.submitcheck = function() {
	return this.each(function(){

		var t = $(this); // get jQuery version of 'this'
		
		$(this).click( function() {
			$(this).attr("disabled","disabled")
			$(this).val("Please wait...")
			$("form", t).submit();
		})
	
	})

}

$.fn.quickAddRemove = function(page){
	return this.each(function(){
		var t = $(this);
		
		t.click( function(){
			var p = t.parent();
			var u = t.attr('href');
			
			$.ajax({
				type: "GET",
				url: u,
				success: function(){
				
					if (t.attr('title') == 'Add') {
						t.parent().append('<img src="/static/v5/images/icon/tick.png" alt="Added" title="Added" width="16" height="16" class="iconTick" /> Added');
					} else {
						if (page =='full') {
							t.replaceWith('<span style="color:#CCC;">Removed</span>');
						} else {
							p.fadeOut();
						}
					}
					$('span', p).highlightFade();
					t.replaceWith(t.text());
				}
				
			});
			
			return false;
		});
		
	});
};
	
$.fn.textToInput = function(){
	return this.each(function(){
		var t = $(this);
		
		t.click( function(){
			$('input:text').val(t.attr('title'));
			return false;
		});
	})
};
	
$.fn.removeElement = function(){
	return this.each(function(){
		var t = $(this);
		
		$('a',t).click( function(){
			var p = $(this).parent();
			p.fadeOut();
			return false;
		});
	})
};