$(document).ready(function() {
	// === site wide ===
	
	flashMessage();
	
	$('.new-window').live('click', function() {
		window.open($(this).attr('href'));
		
		return false;
	});

	// === logged in site wide ===
	
	$('#friend_search_terms').bind("focus", function(e){
		if ($(this).val() == 'Find a friend...') {
			$(this).val('');
		}
		
		$(this).removeClass('form_element_description');
	});
	
	$('#friend_search_terms').bind("blur", function(e){
		if ($(this).val() == '') {
			$(this).addClass('form_element_description');
			
			$(this).val('Find a friend...');
		}
	});
	
	$('#find_friends_form').bind('submit', function(){
		if ($("#friend_search_terms").val() != '' && $('#friend_search_terms').val() != 'Find a friend...') {
			$('#nav .friends .search .results').empty();
			$('#nav .friends .search .loading_68aa06').show();
		
			$.ajax({
				type: "POST",
				url: "/friends/find",
				data: { friend_search_terms: $("#friend_search_terms").val() },
				dataType: 'json',
				success: function(response) {
					if (response.error && response.error == 'not_logged_in') {
						window.location = '/wish-list';
						return;
					}
					
					$('#nav .friends .search .loading_68aa06').hide();
					$('#find_friend_information').hide();
					$('#nav .friends .search .description').hide();
						
					if (response.friends.length == 0) {
						$('#find_friend_information').html('No friends found :(').show();
					}
					else {
						for (x in response.friends) {
							friend = document.createElement('div');
							$(friend).addClass('friend');
							$(friend).attr('title', 'Click to add as a friend');
							friend.onclick = function() { addFriend(this); }
							
							details = document.createElement('div');
							$(details).addClass('details');
							
							display_name = document.createElement('div');
							$(display_name).addClass('display_name');
							$(display_name).html(response.friends[x].display_name);
							
							$(details).append(display_name);
							
							username = document.createElement('div');
							$(username).addClass('username');
							$(username).html(response.friends[x].username);
							if (response.friends[x].username != response.friends[x].display_name) {
								$(username).addClass('force_hide');
							}
							
							$(details).append(username);
							
							profile_image = document.createElement('img');
							$(profile_image).addClass('profile_image');
							if (response.friends[x].has_avatar == 0) {
								$(profile_image).addClass('default');
							}
							$(profile_image).attr('src', '/assets/images/site/avatars/'+(response.friends[x].has_avatar == 1 ? response.friends[x].id+'/' : '')+'70x.png');
							
							break_div = document.createElement('div');
							$(break_div).addClass('break');
							
							$(friend).append(details, profile_image, break_div);
							
							$('#nav .friends .search .results').append(friend);
						}
					}
				}
			});
			
			pageTracker._trackEvent('member', 'friend-search', $("#friend_search_terms").val());
		}
		
		return false;
	});
	
	// === /wish-list and remote wish list ===

	$('.view-at-store').live('click', function(){
		window.open($(this).attr('href'));
		
		pageTracker._trackEvent('wish', 'view-at-store', $(this).attr('href'));
		
		return false;
	});

	$('.reserve').live('click', function(){
		$.ajax({
			type: "POST",
			url: $(this).attr('href'),
			data: { ajax: true },
			dataType: 'json',
			success: function(response) {
				if (response.error) {
					if (response.error != 'not_logged_in') {
						flashMessage(response.error, '#content .error');
					}
				}
				else {
					flashMessage('This wish is now reserved. Click on Reservations to view and buy it.', '#content .success');
					
					$('#nav .options li.reservations a .count span').html(parseInt($('#nav .options li.reservations a .count span').html()) + 1);
					
					pageTracker._trackEvent('wish', 'reserved', response.wish.id);
				}
				
				$('.wish-list-selector li:not(.off)').click();
			}
		});
		
		return false;
	});
	
	$('.given').live('click', function(){
		$.ajax({
			type: "POST",
			url: $(this).attr('href'),
			dataType: 'json',
			success: function(response) {
				if (response.error) {
					if (response.error == 'not_logged_in') {
						window.location = '/wish-list';
						return;
					}
					else {
						flashMessage(response.error, '#content .error');
					}
				}
				else {
					$('.wish-list-selector li:not(.off)').click();
					flashMessage('Great! I\'m sure they\'ll love it!', '#content .success');
					
					pageTracker._trackEvent('wish', 'given', response.wish.id);
				}
			}
		});
		
		return false;
	});
	
	$('.remove').live('click', function(){
		$.ajax({
			type: "POST",
			url: $(this).attr('href'),
			dataType: 'json',
			success: function(response) {
				if (response.error) {
					if (response.error == 'not_logged_in') {
						window.location = '/wish-list';
						return;
					}
					else {
						flashMessage(response.error, '#content .error');
					}
				}
				else {
					$('.wish-list-selector li:not(.off):not(#friends,#reservations)').click();
					flashMessage('Your wish has been removed.', '#content .success');
					
					$('#nav .options li.mine a .count span').html(parseInt($('#nav .options li.mine a .count span').html()) - 1);
					
					pageTracker._trackEvent('wish', 'removed', response.wish.id);
				}
			}
		});
		
		return false;
	});
	
	// === /wish-list/add form ===
	add_wish_form_element_descriptions = {}
	add_wish_form_element_descriptions.url = 'e.g. http://www.amazon.com/xbox';
	add_wish_form_element_descriptions.name = 'e.g. Xbox 360';
	add_wish_form_element_descriptions.description = 'e.g. The Xbox that comes with Duke Nukem Forever';
	add_wish_form_element_descriptions.tags = 'e.g. computer game, xbox, for my birthday';
	add_wish_form_element_descriptions.image_manual_url = 'e.g. http://wishlings.com/assets/images/site/layout/pressies.png';
	
	if ($('#url').val() == '' || $('#url').val() == add_wish_form_element_descriptions.url) {
		$('#url').val(add_wish_form_element_descriptions.url);
		$('#url').addClass('form_element_description');
	}
	
	if ($('#name').val() == '' || $('#name').val() == add_wish_form_element_descriptions.name) {
		$('#name').val(add_wish_form_element_descriptions.name);
		$('#name').addClass('form_element_description');
	}
	
	if ($('#description').val() == '' || $('#description').val() == add_wish_form_element_descriptions.description) {
		$('#description').val(add_wish_form_element_descriptions.description);
		$('#description').addClass('form_element_description');
	}
	
	if ($('#tags').val() == '' || $('#tags').val() == add_wish_form_element_descriptions.tags) {
		$('#tags').val(add_wish_form_element_descriptions.tags);
		$('#tags').addClass('form_element_description');
	}
	
	if ($('#image_manual_url').val() == '' || $('#image_manual_url').val() == add_wish_form_element_descriptions.image_manual_url) {
		$('#image_manual_url').val(add_wish_form_element_descriptions.image_manual_url);
		$('#image_manual_url').addClass('form_element_description');
	}
	
	$('#url,#name,#description,#tags,#image_manual_url').bind("focus", function(e){
		if ($(this).val() == add_wish_form_element_descriptions[$(this).attr('id')]) {
			$(this).val('');
		}
		
		$(this).removeClass('form_element_description');
	});
	
	$('#url,#name,#description,#tags,#image_manual_url').bind("blur", function(e){
		if ($(this).val() == '') {
			$(this).addClass('form_element_description');
			
			$(this).val(add_wish_form_element_descriptions[$(this).attr('id')]);
		}
	});
	
	$("#login").bind("submit", function(e){
		$.ajax({
			type: "POST",
			url: "/account/login",
			data: $("#login").serialize(),
			dataType: 'json',
			success: function(response) {
				$('#username_error').html('');
				$('#password_error').html('');
				$('#login_error').html('');
				
				$('#username_error').hide();
				$('#password_error').hide();
				$('#login_error').hide();
				$('#login_information').hide();
				
				if (response.errors) {
					for (x in response.errors) {
						$('#'+x).html(response.errors[x]);
						$('#'+x).show();
					}
				}
				else {
					window.location = $('#redirect_to').val() != undefined ? $('#redirect_to').val() : '/wish-list';
				}
			}
		});
		
		return false;
	});
	
	$('#url').bind('keydown', function(e){
		scrapeWishURL();
	});
	
	$('#image_manual_url_show').click(function(e){
		$('#image_manual_url_container').show();
		
		$('#wish-list_add #images .description .without_image_manual_url').hide();
		$('#wish-list_add #images .description .with_image_manual_url').show();
		
		return false;
	});
	
	$('#wish_priority_high,#wish_priority_medium,#wish_priority_low').bind('click', function(e){
		// matches the text within the list lis
		priorities = {'High': 3, 'Medium': 2, 'Low': 1}
		
		$('#wish_priority_high,#wish_priority_medium,#wish_priority_low').removeClass('selected');
		
		$(this).addClass('selected');
		
		object_item = 'priorities.'+$(this).html();
		
		$('#priority').val(eval(object_item));
	});
	
	$('.wish-list-selector li').bind('click', function(e){
		$('#wishes').empty();
		$('#wishes_loading').show();
	
		list_item = $(this).attr('id');
		// Bit hacky, this should be improved
		if (list_item == 'custom') {
			list_item = 'friends';
		}
				
		$('#nav .options li').not('#'+list_item).removeClass('selected');
		$('#nav .options li.'+list_item).addClass('selected');
		
		if (typeof(wish_list_selector_options) == 'undefined') {
			wish_list_selector_options = {}
		}
		wish_list_selector_options.fetch = list_item;
		
		$.ajax({
			type: "post",
			url: "/wish-list/get",
			data: wish_list_selector_options,
			dataType: 'json',
			success: function(response) {
				if (response.errors) {
					if (response.errors == 'not_logged_in') {
						window.location = '/wish-list';
						return;
					}
				}
			
				if (typeof(wish_list_selector_options.custom_button) == 'undefined') {
					$('.wish-list-selector li').not('#'+list_item).addClass('off');
					$('#'+list_item).removeClass('off');
				}
				else {
					$('.wish-list-selector li').addClass('off');
					$('#custom').removeClass('off');
				}
				
				$('#wishes_loading').hide();
				
				// there are no entries
				if (response.wishes.length == 0) {
					switch (list_item) {
						case 'all':
							flashMessage('Welcome to your wish list. Please add a wish above.', '#content .information');
						break;
						case 'mine':
							flashMessage('You don\'t have any wishes. Please add one above.', '#content .information');
						break;
						case 'reservations':
							flashMessage('You have no reservations. Yey!', '#content .information');
						break;
						case 'friends':
							if (typeof(wish_list_selector_options.username) != 'undefined') {
								flashMessage('Your friend doesn\'t have any wishes. Maybe you should poke them.', '#content .information');
							}
							else {
								flashMessage('Your friends don\'t have any wishes. Maybe you should poke them.', '#content .information');
							}
						break;
					}
				}
				
				for (x in response.wishes) {
					// build an entry
					wish = document.createElement('div');
					$(wish).addClass('wish');
					$(wish).addClass('member'+response.wishes[x].member_id);
					
					bar = document.createElement('div');
					$(bar).addClass('bar');
					
					profile_image = document.createElement('img');
					$(profile_image).addClass('profile_image');
					$(profile_image).attr('src', '/assets/images/site/avatars/'+(response.wishes[x].has_avatar == 1 ? response.wishes[x].member_id+'/' : '')+'24x24.png');
					
					action = document.createElement('div');
					$(action).addClass('action');
					$(action).html(response.wishes[x].action);
					
					actions = document.createElement('ul');
					$(actions).addClass('actions');
					
					switch (response.wishes[x].type) {
						case 'mine':
							buy = document.createElement('li');
							$(buy).html('<a href="/'+response.wishes[x].username+'/'+response.wishes[x].name_slug+'/buy" class="view-at-store">Buy</a>/');
							edit = document.createElement('li');
							$(edit).html('<a href="/wish-list/add/'+response.wishes[x].id+'?TB_iframe=true&width=556&height=410" class="thickbox">Edit</a>/');
							remove_li = document.createElement('li');
							$(remove_li).html('<a href="/wish-list/remove/'+response.wishes[x].id+'" class="remove">Remove</a>');
							$(actions).append(buy, edit, remove_li);
						break;
						
						case 'friends':
							reserve = document.createElement('li');
							if (response.wishes[x].status == 'added') {
								$(reserve).html('<a href="/wish-list/reserve/'+response.wishes[x].id+'" class="reserve">Buy for '+response.wishes[x].display_name_first+'</a>/');
							}
							else {
								$(reserve).html('<span>Reserved</span> /');
							}
							view_at_store = document.createElement('li');
							$(view_at_store).html('<a href="/'+response.wishes[x].username+'/'+response.wishes[x].name_slug+'/buy" class="view-at-store">View at Store</a>');
							$(actions).append(reserve, view_at_store);
						break;
						
						case 'reservations':
							buy = document.createElement('li');
							$(buy).html('<a href="/'+response.wishes[x].username+'/'+response.wishes[x].name_slug+'/buy" class="view-at-store">Buy</a>/');
							given = document.createElement('li');
							$(given).html('<a href="/wish-list/given/'+response.wishes[x].id+'" class="given">I\'ve given this</a>/');
							cancel = document.createElement('li');
							$(cancel).html('<a href="/wish-list/cancel/'+response.wishes[x].id+'" onclick="cancelReservation(this); return false;">Cancel</a>');
							$(actions).append(buy, given, cancel);
						break;
					}
					
					$(bar).append(profile_image, action, actions);
					
					break_div = document.createElement('div');
					$(break_div).addClass('break');
					
					affiliated = {}
					
					if (response.wishes[x].affiliated == 1) {
						affiliated = document.createElement('div');
						$(affiliated).addClass('affiliated');
						
						message = document.createElement('div');
						$(message).addClass('message error static force_show');
						$(message).text(response.wishes[x].affiliated_message);
						
						$(affiliated).append(message);
					}
					
					left = document.createElement('div');
					$(left).addClass('left');
					wish_image_img = document.createElement('img');
					$(wish_image_img).attr('src', response.wishes[x].wish_image_url ? response.wishes[x].wish_image_url : '/assets/images/site/layout/wish-list-no-img.png');
					
					if (response.wishes[x].priority != null) {
						priority = document.createElement('div');
						$(priority).addClass('priority');
						$(priority).addClass('priority'+response.wishes[x].priority);
						switch(response.wishes[x].priority) {
							case '1':
								$(priority).html('Low Priority');
							break;
							case '2':
								$(priority).html('Medium Priority');
							break;
							case '3':
								$(priority).html('High Priority');
							break;
						}
						
						$(left).append(priority);
					}
					
					$(left).append(wish_image_img);
					
					name_div = document.createElement('div');
					$(name_div).addClass('name');
					$(name_div).html(response.wishes[x].name.length > 73 ? trim(response.wishes[x].name.substr(0,73))+'...' : response.wishes[x].name);
					
					description_div = document.createElement('div');
					$(description_div).addClass('description');
					$(description_div).html(response.wishes[x].description.length > 250 ? trim(response.wishes[x].description.substr(0,250))+'...' : response.wishes[x].description);
					
					$(wish).append(bar, break_div, affiliated, left, name_div, description_div);
					
					if (countObjectProperties(response.wishes[x].tags) > 0) {
						tags = document.createElement('ul');
						$(tags).addClass('tags');
						
						for (y in response.wishes[x].tags) {
							li = document.createElement('li');
							$(li).html(response.wishes[x].tags[y]);
							
							$(tags).append(li);
						}
						
						$(wish).append(tags);
					}
					
					wish_separator = document.createElement('div');
					$(wish_separator).addClass('wish_separator');
					
					$('#wishes').append(wish, wish_separator);
				}
				
				tb_init("a.thickbox:not(#add,#avatar)");
			}
		});
	});
});

// === layout ===

function flashMessage(message, location, window, auto_hide) {
	if (location == undefined) location = '';
	if (auto_hide == undefined) auto_hide = true;

	if (message) {
		// empty all existing non-static errors
		eval(window ? window : this).$(".message:not(.static) div").empty();
	
		// add our error message
		eval(window ? window : this).$(location).html(message);
	}
	
	// animate
	eval(window ? window : this).$(location+".message:not(.static):not(:empty)").animate( { top: "0px" }, 0 ).slideDown('medium').fadeOut(1000).fadeIn(1000).animate({opacity: 1.0}, 3000);
	
	if (auto_hide) {
		eval(window ? window : this).$(location+".message:not(.static):not(:empty)").slideUp();
	}
}

// === /wish-list ===

function cancelReservation(element) {
	$.ajax({
		type: "POST",
		url: $(element).attr('href'),
		dataType: 'json',
		success: function(response) {
			if (response.error) {
				if (response.error == 'not_logged_in') {
					window.location = '/wish-list';
					return;
				}
				else {
					flashMessage(response.error, '#content .error');
				}
			}
			else {
				$('.wish-list-selector li:not(.off)').click();
				flashMessage('The reservation has been cancelled.', '#content .success');
				
				$('#nav .options li.reservations a .count span').html($('#nav .options li.reservations a .count span').html() - 1);
			}
		}
	});
}

function addFriend(div) {
	$.ajax({
		type: "POST",
		url: "/friends/add/"+$(div).find('.details .username').html(),
		dataType: 'json',
		success: function(response) {
			if (response.error) {
				if (response.error == 'not_logged_in') {
					window.location = '/wish-list';
					return;
				}
			}
			else {
				if ($('#nav div.friends table').html() == null) {
					table = document.createElement('table');
					$('#nav div.friends').prepend(table);
				}
			
				tr = $('#nav div.friends tr:last');
			
				if ($("#nav div.friends tr:last td").size() == 7 || $("#nav div.friends tr:last td").size() == 0) {
					tr = document.createElement('tr');
					$("#nav div.friends table").append(tr);
				}
				
				td = document.createElement('td');
				a = document.createElement('a');
				$(a).attr('href', '/wish-list/friends/'+$(div).find('.details .username').html());
				$(a).attr('title', $(div).find('.details .display_name').html());
				img = document.createElement('img');
				img.width = 24;
				img.height = 24;
				img.alt = $(div).find('.details .display_name').html();
				img.src = $(div).find('.profile_image').attr('src').replace('70x', '24x24');
				
				$(a).append(img);
				$(td).append(a);
				$(tr).append(td);
				
				// update the friend count
				$('#nav .options li.friends a .count span').html($("#nav div.friends td").size());
			
				$(div).slideUp();
				
				pageTracker._trackEvent('member', 'friend-added', $(div).find('.details .username').html());
			}
		}
	});
}

var SCRAPE_WISH_URL_TIMER = null;
function scrapeWishURL(delay) {
	if(SCRAPE_WISH_URL_TIMER) {
		clearTimeout(SCRAPE_WISH_URL_TIMER);
	}
	SCRAPE_WISH_URL_TIMER = setTimeout('scrapeWishURLNow()', (delay ? delay : 2000));
}

SCRAPING_WISH_URL = false;
function scrapeWishURLNow() {
	if (SCRAPING_WISH_URL) return;
	
	SCRAPING_WISH_URL = true;
	  
	// add http:// if no protocol exists
	if ($('#url').val().indexOf('://') == -1 && $('#url').val() != '') {
		$('#url').val('http://'+$('#url').val());
	}
	
	if($('#url').val() == '') { 
		return false;
	}
	
	$('#url_error').hide();
	
	if ($('#name').val() == '' || $('#name').val() == add_wish_form_element_descriptions.name) {
		$('#name_loading').show();
	}
	
	if ($('#description').val() == '' || $('#description').val() == add_wish_form_element_descriptions.description) {
		$('#description_loading').show();
	}
	
	if ($('#tags').val() == '' || $('#tags').val() == add_wish_form_element_descriptions.tags) {
		$('#tags_loading').show();
	}
	
	$('#images').hide();
	$('#images_loading').show();
	
	$.ajax({
		type: "post",
		url: "/wish-list/scrape_wish_url",
		data: { url: escape($('#url').val()), 'wish_image_id': $('#wish_image_id').val() },
		dataType: 'json',
		success: function(response) {
			SCRAPING_WISH_URL = false;
			if (response.errors) {
				for (x in response.errors) {
					$('#'+x).html('<p>'+response.errors[x]+'</p>');
					$('#'+x).show();
			
					$('#name_loading').hide();
					$('#description_loading').hide();
					$('#tags_loading').hide();
					$('#images_loading').hide();
				}
			}
			else {
				if (response.page) {
					// remove existing images from table
					table = document.getElementById('wish_images');
					tbody = document.getElementById('wish_images_tbody');
					table.removeChild(tbody);
				
					tbody = document.createElement('tbody');
					tbody.id = 'wish_images_tbody';
					table.appendChild(tbody);
				
					// wish title
					if (($('#name').val() == '' || $('#name').val() == add_wish_form_element_descriptions.name) && response.page.title) {
						$('#name').removeClass('form_element_description');
						$('#name').val(response.page.title);
					}
					$('#name_loading').hide();
					
					// wish description
					if (($('#description').val() == '' || $('#description').val() == add_wish_form_element_descriptions.description) && response.page.description) {
						$('#description').removeClass('form_element_description');
						$('#description').val(response.page.description);
					}
					$('#description_loading').hide();
					
					// wish tags
					if (($('#tags').val() == '' || $('#tags').val() == add_wish_form_element_descriptions.tags) && response.page.tags) {
						$('#tags').removeClass('form_element_description');
						$('#tags').val(response.page.tags);
					}
					$('#tags_loading').hide();
					
					// wish images
					if (response.page.image_urls) {
						cnt = 0;
						for (x in response.page.image_urls) {
							// create new tr
							if (cnt % 4 == 0) {
								tr = document.createElement('tr');
								$('#wish_images').append(tr);
							}
							
							// add td
							td = document.createElement('td');
							if (cnt == 3) td.className = 'last';
							a = document.createElement('a');
							$(a).attr('title', 'Click to choose this image');
							a.className = 'wish_image_url'+($('#wish_image_id').val() == x ? ' selected' : '');
							a.href = '#';
							a.onclick = function(){ selectWishImage(this); return false; }
							a.id = 'wish_image_url_'+x;
							img = document.createElement('img');
							img.src = response.page.image_urls[x];
							a.appendChild(img);
							td.appendChild(a);
							
							tr.appendChild(td); 
						
							cnt++;
						}
					}
					
					$('#images_loading').hide();
					
					if (countObjectProperties(response.page.image_urls) > 0) {
						$('#images').show();
						$('.wish_image_url').show(2000);
					}
					else {
						$('#url_error').html("<p>Sorry, we couldn't find any images at this link</p>");
						$('#url_error').show();
					}
				}
			}
		}
	});
}

function selectWishImage(element){
	// deselect the selected image (if any)
	$('.wish_image_url').removeClass('selected');
	
	$('#wish_image_id').val(element.id.replace('wish_image_url_', ''));
	
	$(element).addClass('selected');
}

function countObjectProperties(object) {
	var count = 0;
	for (k in object) if (object.hasOwnProperty(k)) count++;
	
	return count;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}