def updateprofile(request):
	# Require login.
	if not (request.user.is_authenticated()):
		return redirect_to_login(request.get_full_path())
	profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)		
	request.user.first_name=request.POST['first_name']
	request.user.last_name=request.POST['last_name']
	request.user.email=request.POST['email']
	request.user.save()

	if profile_form.is_valid():
		profile_form.save()
	else:
		profile_form = ProfileForm(instance=request.user.profile)
	return HttpResponseRedirect("/edit/")
def profile(request):
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)

        if profile_form.is_valid():
            profile_form.save()
            return HttpResponseRedirect('/profile/')

        else:
            profile_form = ProfileForm(instance=request.user.profile)

        return render_to_response('profile.html', {'form': profile_form})
    else:
        profile_form = ProfileForm(instance=request.user.profile)
        return render_to_response('profile.html', {
            'form': profile_form,
            'test': request.user.profile.site,
            'blah': request.user.profile.picture.url
        },
                                  context_instance=RequestContext(request))
def updateprofile(request):
    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())
    profile_form = ProfileForm(request.POST,
                               request.FILES,
                               instance=request.user.profile)
    request.user.first_name = request.POST['first_name']
    request.user.last_name = request.POST['last_name']
    request.user.email = request.POST['email']
    request.user.save()

    if profile_form.is_valid():
        profile_form.save()
    else:
        profile_form = ProfileForm(instance=request.user.profile)
    return HttpResponseRedirect("/edit/")
def profile(request):
	if request.method == 'POST':
		profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)

		if profile_form.is_valid():
			profile_form.save()
			return HttpResponseRedirect('/profile/')

		else:
			profile_form = ProfileForm(instance=request.user.profile)

		return render_to_response('profile.html', { 'form' : profile_form })
	else:
		profile_form = ProfileForm(instance=request.user.profile)
		return render_to_response('profile.html', { 'form' : profile_form, 'test' : request.user.profile.site, 'blah' : request.user.profile.picture.url }, context_instance=RequestContext(request))
def edit(request):
    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    recs = Recommendation.objects.filter(user=request.user).order_by('-added')
    category_types = CategoryType.objects.all()
    all_categories = Category.objects.all()
    context = {
        'recs': recs,
        'category_types': category_types,
        'user': request.user,
        'cat_check_htmls': []
    }
    books_in_c = {}
    for c in all_categories:
        books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                              .distinct()]
    print >> sys.stderr, repr(books_in_c)
    for rec in recs:
        b = ''
        for ct in category_types:
            b += '<h4>%s</h4>' % ct.description
            for c in ct.get_categories():
                b += '<span class="checkbox-container"><input class="form-update-checkbox-' + rec.book.gid + '" type="checkbox" name="{0}" id="{1}{0}"'.format(
                    c.slug, rec.id)
                if rec in books_in_c[c]:
                    b += 'checked="checked" '
                b += '/><label for="%d%s">%s</label></span>' % (rec.id, c.slug,
                                                                c.name)
        context['cat_check_htmls'].insert(0, b)

    if 'keywords' in request.GET:
        context['results'] = gbooks.search(request.GET['keywords'])
    elif 'gid' in request.POST:
        if 'action' in request.POST:
            if request.POST['action'] == 'update':
                b = Book.objects.get(gid=request.POST['gid'])
                r = Recommendation.objects.get(user=request.user, book=b)
                for c in Category.objects.all():
                    if c.slug in request.POST:
                        c.books.add(b)
                    else:
                        c.books.remove(b)
                r.comment = request.POST['blurb']
                r.save()
                print >> sys.stderr, repr(request.POST)
            elif request.POST['action'] == 'delete':
                b = Book.objects.get(gid=request.POST['gid'])
                r = Recommendation.objects.get(user=request.user, book=b)
                if len(Recommendation.objects.filter(book=r.book)) == 1:
                    os.unlink(os.path.join(BOOK_COVERS, r.book.cover_image))
                    r.book.delete()
                r.delete()
            # Redirect to avoid refresh issues
            return HttpResponseRedirect("/edit/")
    elif 'profileaction' in request.POST:
        if request.POST['profileaction'] == 'update':
            profile_form = ProfileForm(request.POST,
                                       request.FILES,
                                       instance=request.user.profile)

            request.user.first_name = request.POST['first_name']
            request.user.last_name = request.POST['last_name']
            request.user.email = request.POST['email']
            request.user.save()

            if profile_form.is_valid():
                profile_form.save()
                return HttpResponseRedirect('/edit/')

            else:
                profile_form = ProfileForm(instance=request.user.profile)
                return HttpResponseRedirect('/edit/')

            #return render_to_response('edit.html', { 'form' : profile_form })
    profile_form = ProfileForm(instance=request.user.profile)
    # Go.
    context['form'] = profile_form
    if request.user.profile.picture:
        context['pictureurl'] = request.user.profile.picture.url
    context['siteurl'] = request.user.profile.site
    context['firstname'] = request.user.first_name
    context['lastname'] = request.user.last_name
    context['email'] = request.user.email
    context['sitename'] = settings.SITE_NAME
    return render_to_response('edit.html',
                              context,
                              context_instance=RequestContext(request))
def edit(request):    
	# Require login.
	if not (request.user.is_authenticated()):
		return redirect_to_login(request.get_full_path())
			
	recs = Recommendation.objects.filter(user=request.user).order_by('-added')
	category_types = CategoryType.objects.all()
	all_categories = Category.objects.all()
	context = {'recs': recs,
               'category_types': category_types,
               'user': request.user,
               'cat_check_htmls': []}
	books_in_c = {}
	for c in all_categories:
		books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                        .distinct()]
	print >>sys.stderr, repr(books_in_c)
	for rec in recs:
		b = ''
		for ct in category_types:
			b += '<h4>%s</h4>' % ct.description
			for c in ct.get_categories():
				b += '<span class="checkbox-container"><input class="form-update-checkbox-' + rec.book.gid +'" type="checkbox" name="{0}" id="{1}{0}"'.format(c.slug, rec.id)
				if rec in books_in_c[c]:
					b += 'checked="checked" '
				b += '/><label for="%d%s">%s</label></span>' % (rec.id, c.slug, c.name)
		context['cat_check_htmls'].insert(0,b)
             
	if 'keywords' in request.GET:
		context['results'] = gbooks.search(request.GET['keywords'])
	elif 'gid' in request.POST:
		if 'action' in request.POST:
			if request.POST['action'] == 'update':
				b = Book.objects.get(gid=request.POST['gid'])
				r = Recommendation.objects.get(user=request.user,
											   book=b)
				for c in Category.objects.all():
					if c.slug in request.POST:
						c.books.add(b)
					else:
						c.books.remove(b)
				r.comment = request.POST['blurb']
				r.save()
				print >>sys.stderr, repr(request.POST)
			elif request.POST['action'] == 'delete':
				b = Book.objects.get(gid=request.POST['gid'])
				r = Recommendation.objects.get(user=request.user,
											   book=b)
				if len(Recommendation.objects.filter(book=r.book)) == 1:
					os.unlink(os.path.join(BOOK_COVERS, r.book.cover_image))
					r.book.delete()
				r.delete()
			# Redirect to avoid refresh issues
			return HttpResponseRedirect("/edit/")
	elif 'profileaction' in request.POST:
		if request.POST['profileaction'] == 'update':
			profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
			
			request.user.first_name=request.POST['first_name']
			request.user.last_name=request.POST['last_name']
			request.user.email=request.POST['email']
			request.user.save()

			if profile_form.is_valid():
				profile_form.save()
				return HttpResponseRedirect('/edit/')

			else:
				profile_form = ProfileForm(instance=request.user.profile)
				return HttpResponseRedirect('/edit/')

			#return render_to_response('edit.html', { 'form' : profile_form })
	profile_form = ProfileForm(instance=request.user.profile)
	# Go.
	context['form'] = profile_form
	if request.user.profile.picture:
		context['pictureurl'] = request.user.profile.picture.url
	context['siteurl'] = request.user.profile.site
	context['firstname'] = request.user.first_name
	context['lastname'] = request.user.last_name
	context['email'] = request.user.email
	context['sitename'] = settings.SITE_NAME
	return render_to_response('edit.html', context, context_instance=RequestContext(request))