$(function()
{
	Start.init();
	
	var $action_area = $('#action-area');
	
	$action_area.find('div.inner').append('<span id="xhr"></span>')
	
	$xhr = $action_area.find('span#xhr');
	
	$().ajaxStart(function()
	{
		$xhr.addClass('loading');
	});
	
	$().ajaxStop(function()
	{
		$xhr.removeClass('loading');
	});
});

Start =
{
	init:function()
	{
		//Start.init_user_search();
		
		$wishlist = $('#wishlist-tryout');
		$action_area = $('#action-area');
		
		this.show_input_help('register');
		
	},
	
	init_user_search:function()
	{
		$find_wishlist = $('p.find-wishlist');
		
		$find_wishlist.find('a').click(function()
		{
			$find_wishlist.fadeOut(function()
			{
				$.get('/start/find_user_mod',function(data)
				{
					$('#about').append(data).find('form.find-user').hide().fadeIn(function()
					{
						$('form.find-user input:first').focus();
					});
				});
			});
			return false;
		});
	},
	
	focus_error_or_empty:function($container)
	{
		
		// Check for error fields. If found - focus the first one
		if ($container.find('label.error').size())
		{
			$container.find('label.error:first input').focus();
		}
		else // Else focus the first empty one.
		{
			$container.find(':input[value=""]:first').focus(); // Focus the first empty field
		}		
	},
	
	show_input_help:function(module)
	{
		var $form = $('#' + module).find('form');
		
		if (!$form.size())
		{
			return false;
		}
		
		var $help_notes = $form.find('span.input-help');
		
		if (!$help_notes.size())
		{
			return false;
		}
		
		$help_notes.each(function()
		{
			var $this = $(this);
			
			var $input = $this.parent('p').find('input');
			
			$input.focus(function()
			{
				$form.find('p.sel').removeClass('sel');
				$(this).parents('p').addClass('sel');
			});
			
			$input.blur(function()
			{
				$(this).parents('p').removeClass('sel');
			});
		});
	}
};$(function()
{
	ForgotLogin.init();
});

var ForgotLogin =
{
	init:function()
	{
		this.form_submit();
	},
	
	form_submit:function()
	{
		var $container = $('#forgot-login');
		var $form = $container.find('form');
		
		
		$form.submit(function()
		{
			var fields = $form.find(":input").serializeArray();
			
			$.post('/start/forgot_login_mod',
			fields,
			function(data)
			{
				if (data == 'success')
				{
					
					$('#action-area').load('/start/login_sent_mod');
				}
				else
				{
					$container.replaceWith(data);
					ForgotLogin.form_submit();
				}	
			});
			
			return false;
		});
		
		Start.focus_error_or_empty($container);
	}
};$(function()
{
	Login.init();
});

var Login =
{
	init:function()
	{
		Login.form_submit();
	},
	
	form_submit:function()
	{
		var $login = $('#login');
		var $form = $login.find('form');
		
		$form.submit(function()
		{
			var fields = $form.find(":input").serialize();
			
			$.post('/start/login_mod',
			fields,
			function(data)
			{
				var result = '';
				
				if (data.indexOf('json =') != -1)
				{
					data = eval(data);
					
					result = data.result;
				}
					
				if (result == 'success')
				{
					window.location = '/dashboard';
				}
				else
				{
					$login.replaceWith(data);
					Login.form_submit();
				}	
			});
			
			return false;
		});
		
		Start.focus_error_or_empty($login);
	}
};$(function()
{
	Register.init();
});

var Register =
{
	init:function()
	{
		Register.form_submit();
	},
	
	form_submit:function()
	{
		var $register = $('#register');
		var $form = $register.find('form');
		
		$form.submit(function()
		{
			var fields = $form.find(":input").serializeArray();
			
			$.post('/start/register_mod',
			fields,
			function(data)
			{
				if (data.indexOf('json =') != -1) // Check for json string
				{
					data = eval(data); // If it was a json str - make into an obj
					
					if (data.result == 'success')
					{
						window.location = data.redir_to;
					}
					else
					{
						window.location = '/';
					}
				}
				else
				{
					$register.replaceWith(data);
					Register.form_submit();
					Start.show_input_help('register');
				}
			});
			
			return false;
		});	
		
		Start.focus_error_or_empty($register);
	}
};$(function()
{
	Wishlist.init();
});

Wishlist =
{	
	edit_element:'', // Element currently being edited
	
	save_new:'',
		
	init:function()
	{
		var $wishlist = $('#wishlist-tryout');		
		
		Wishlist.init_edit('h2'); // Make h2 editable
		Wishlist.init_edit('li'); // Make li's editable
		
		Wishlist.init_add_wish();	// Add link for adding a wish
		
		Wishlist.toggle_add_button();
		
		Wishlist.save_new = false;	
	},
	
	init_add_wish:function()
	{
		var $wishlist = $('#wishlist-tryout');
		
		$('a.add-wish').click(function() 
		{
			if (Wishlist.in_edit_mode())
			{
				return false;
			}
			
			var new_id = Wishlist.get_new_id();
			
			$wishlist.find('ul').append('<li id="' + new_id + '"></li>'); 	// Append empty li
			Wishlist.init_edit('li');					// Init edit for li's again (to capture the newly added one)
			
			// Trigger click so that it transforms into a textfield
			// Don't know why timeout is needed here, but the click doesn't go thru otherwise. 1 ms is enough though.
			setTimeout(function() {
				$wishlist.find('li:last').trigger('click'); 
			},1);
			
			Wishlist.save_new = true;
			
			return false;
		});
	},
	
	get_new_id:function()
	{
		var $wishlist = $('#wishlist-tryout');
		
		var $wishes = $wishlist.find('li');
		
		// If we have at least one wish..
		// Get the highest id and add 1 to get the new
		if ($wishes.size())
		{
			var li_ids = new Array();

			$wishlist.find('li').each(function(i) {
				li_ids[i] = $(this).attr('id');
			})

			li_ids = li_ids.sort();

			var last_id = li_ids.pop().substr(2);
			var new_id = 'w_' + (parseInt(last_id)+1);
		}
		else // If wishlist is empty
		{
			var new_id = 'w_' + 1;
		}
		
		return new_id;
	},
	
	in_edit_mode:function()
	{
		var $input = $('input.text'); // Get edit textfield
		
		var $textarea = $('textarea#h2'); // Get edit textfield
		
		if ($input.size() || $textarea.size())
		{
			return true;
		}
		else
		{
			return false;
		}
	},
	
	init_edit:function(element_type)
	{	
		$('#wishlist-tryout p.go-on').show();
		
		var $element = $('#wishlist-tryout').find(element_type); // Get wanted element

		$element.each(function()
		{
			if (element_type == 'li') // Only on li's..
			{
				Wishlist.toggle_wish_mod_links($(this));
			}
			
			// Assign edit capabilities on click
			$(this).one('click',function(e)
			{	 				
				if (Wishlist.in_edit_mode())
				{
					return false;
				}
				
				// We dont want edit to show if we're clicking a (delete) link in the element - abort, if so
				if (e.target.nodeName.toLowerCase() == 'a') {return false;} 
				
				var $this = $(this);
				
				Wishlist.edit_element = $this; // Store element in property
				
				$this.find('a').remove(); // Remove eventual links from the element, otherwise that text is gonna show up in the textfield too.
				
				var submit_area = '<p class="submit-area cf"><a href="#" class="button-sml save"><span class="save"><span>Spara</span></span></a><a href="#" class="button-sml cancel"><span class="cancel"><span>Avbryt</span></span></a></p>';
				
				if (element_type == 'li')
				{
					// Get text and prepere the textfield
					var value = $this.text(); 
					
					var textfield = '<input type="text" class="text ' + element_type + '" name="' + element_type + '" id="' + element_type + '" value="' + value + '" />';
					
					$this.html(textfield + submit_area); // Replace elements value with textfield with just that value
					
					var $input = $("input#" + element_type); // Get the input. Its done by looking for an input with the element type of the original element as id					
				}
				else if (element_type == 'h2')
				{
					$this.wrapInner('<textarea class="' + element_type + '" name="' + element_type + '" id="' + element_type + '"></textarea>');
					
					var $input = $("textarea#" + element_type);
					
					$this.after(submit_area);
				}
				
				$('div.list a.add-wish').hide();
				
				$('#wishlist-tryout p.go-on').hide();
			
				$input.focus(); // Focus textfield
				
				Wishlist.init_save($input);
			
				//Wishlist.init_stop_edit(false); // Init cancel.
				
				return false;
			});
		});
	},
	
	init_save:function($input)
	{
		// Look for key press
		$input.keyup(function(e)
		{
			if(e.keyCode == 13) // on enter
			{
				Wishlist.stop_edit(false); // Cancel edit
			}
		});
		
		var $submit_area = $('p.submit-area');
		
		$submit_area.find('a.save').click(function()
		{
			Wishlist.stop_edit(false);
			return false;
		});
		
		$submit_area.find('a.cancel').click(function()
		{
			Wishlist.stop_edit(true);
			return false;
		});
	},
	
	init_stop_edit:function()
	{
		// Abort edit mode if user clicks anywhere outside the textfield
		var $body = $('html');
		$body.click(function(e)
		{	
			Wishlist.stop_edit(false);
			return false;
		});
	},
	
	stop_edit:function(cancel)
	{		
		var $element = Wishlist.edit_element;	// Get element being edited from obj prop
		var element_type = $element.get()[0].nodeName.toLowerCase(); // Get type of element (nodeName)
	
		var $input;
		
		$input = (element_type == 'li') ? $('input.text') : $('textarea');
		
		// Abort if textfield isn't visible or the edited element isn't found
		if (!$input.size() || $element === '') { return false; }
		
		var input_value = $input.val(); // Get value
		
		$element.text(input_value); // Replace input with only the text from it.
		
		// If the element doesn't contain any text at all (another way of deleting) - remove it
		if ((input_value === '' || cancel === true) && element_type == 'li') 
		{
			Wishlist.delete_wish($element,input_value);
		}
		else
		{
			if (element_type == 'h2')
			{
				$('p.submit-area').remove();
			}
			
			Wishlist.save(input_value);
		}
		
		Wishlist.init_edit(element_type);	// Init edit actions for this kind of element again
	},
	
	save:function(input_value)
	{
		var action = '';
		
		var $element = Wishlist.edit_element;	// Get element being edited from obj prop
		
		var element_type = $element.get()[0].nodeName.toLowerCase(); // Get type of element (nodeName)
		
		if (element_type == 'li')
		{
			var key = $element.attr('id');
		}
		
		if (Wishlist.save_new)
		{
			action = 'add';
			Wishlist.save_new = false;
		}
		else
		{
			action = 'update';			
		}
		
		$.post('/start/save_temp_wish',
		{
			'key':key,
			'action':action,
			'element_type':element_type,
			'value':input_value
		},
		function(data)
		{
			
			
			Wishlist.toggle_add_button();
			Wishlist.edit_element = '';	// Empty obj prop that stored the recently edited element			
		});
	},
	
	toggle_wish_mod_links:function($elem)
	{	
		// Toggle delete link
		$elem.hover(function() // Mouseover
		{
			if (Wishlist.in_edit_mode())
			{
				return false;
			}
			
			// Abort if link is already present, if we're in sort mode or edit mode
			if ($elem.find('a').size() || $('ul.sort').size() || $('input.text').size())
			{
				return false;
			}
			
			$elem.append('<a href="#" class="delete">Radera?</a>'); // Append delete link
			
			$elem.find('a').click(function()	// Assign delete method to it
			{
				Wishlist.delete_wish($(this));
				return false;
			});
		},
		function() // Mouseout - remove delete link
		{
			$elem.find('a.delete').remove();
		});
	},
	
	delete_wish:function($this)
	{
		// If $this isn't a <li>, it's an <a> and is a child of <li>. So get it.
		if ($this.get()[0].nodeName.toLowerCase() != 'li')
		{
			$this = $this.parent('li');
		}
	
		var key = $this.attr('id');

		$.post('/start/delete_temp_wish',
		{	
			'key':key
		},
		function()
		{
			// Only fade out if it's a forced delete (row contains text)
			// If it's empty - we dont want it to fade.
			if ($this.text() == '')
			{
				Wishlist.delete_wish_callback($this)
			}
			else
			{
				$this.fadeOut(function() // Just fade out clicked wish and then remove it from DOM
				{
					Wishlist.delete_wish_callback($this)
				});
			}
		});
	},
	
	delete_wish_callback:function($row)
	{
		$row.remove();
		Wishlist.toggle_add_button();
	},
	
	toggle_add_button:function()
	{
		var $wishlist_container = $('#wishlist-tryout');
		
		var $wishlist = $wishlist_container.find('ul');
		
		var $wishes = $wishlist.find('li');
		
		var num_wishes = $wishes.size();
		
		var $add_button = $wishlist_container.find('a.add-wish');
		
		var $add_note = $wishlist_container.find('p.note');
		
		var wishlist_height = parseInt($wishlist.css('height'));
		
		if (num_wishes > 4 || wishlist_height > 160)
		{
			$add_button.hide();
			
			if (!$add_note.size())
			{
				$add_button.after('<p class="note">Klicka på fortsätt om du vill lägga till fler önskningar.</p>');
			}
		}
		else
		{
			$add_button.show();
			$add_note.remove();
		}
	}
};