# ecp gallery module, © 2004 ecp, douglas savitsky
# protected by the GNU General Public License
# there is no warranty provided with this code

import cPickle
import os.path

_path = '****'
_dbpath = '****'

def _XT(ci, i):
	if str(ci) == str(i):
		return '<b>%s</b>' % i
	else:
		return '%s' % i
	
def _next(g, i, db):
	x = db[g].keys()
	x.sort()
	if str(i) == str(x[-1]):
		return '1'
	else:
		return str(int(i) + 1)

def _prev(g, i, db):
	i = int(i) - 1
	if i == 0:
		x = db[g].keys()
		x.sort()
		return str(x[-1])
	else:
		return str(i)

def index(req, gallery=None, img=None):
	l = []
	f = open(_path + '_head', 'r')
	s = f.read()
	f.close()
	db = cPickle.load(open(os.path.join(_dbpath, '_gallery2.db')))
	l.append(s.replace('WIDTH=600', 'WIDTH=800').replace('CELLPADDING=4', 'CELLPADDING=8').replace('CELLSPACING=1', 'CELLSPACING=0'))
	l.append('<td colspan=2> </td><tr>')
	l.append('<TD ALIGN="LEFT" VALIGN="TOP" WIDTH = 150 class="bar_text" bgcolor="#ffffff">')
	l.append('<TABLE BGCOLOR="FF5300" CELLPADDING=6 CELLSPACING=2 WIDTH=100%><TR><TD bgcolor="#dddddd" width=100% class="bar_text">')
	g = db.keys()
	g.sort()
	l.append('<b>Galleries:</b></td>')
	l.append('<TR><TD bgcolor="#dddddd" width=100% class="bar_text">')
	for i in g:
		l.append('<A HREF="./?gallery=%s&img=1">%s</A><BR>' % (i, _XT(gallery,i)))

	l.append('</TD></TABLE></TD>')
	
	l.append('<TD ALIGN="CENTER" VALIGN="TOP" WIDTH=650 bgcolor="#ffffff" class="bar_text">')
	if img and gallery:
		l.append('<IMG SRC="../../images/%s">' % db[gallery][int(img)])
	else:
		l.append('<IMG SRC="../../images/ecpsoftware_ico.jpg">')
	l.append('</TD>')
	l.append('<tr>')
	if img and gallery:
		l.append('<TD align="center" colspan=2 class="bar_text" BGCOLOR=#ffffff>')
		#l.append('<p>')
		e = db[gallery].keys()
		e.sort()
		l.append('<TABLE BGCOLOR="FF5300" CELLPADDING=6 CELLSPACING=2 WIDTH=100%><TR><TD bgcolor="#dddddd" width=100% class="bar_text" align="center">')
		l.append('<A HREF="./?gallery=%s&img=%s">previous</a>' % (gallery, _prev(gallery, img, db)))
		l.append('%s' % ' '.join(['<A HREF="./?gallery=%s&img=%s">%s</A>' % (gallery, j, _XT(img, j)) for j in e]))
		l.append('<A HREF="./?gallery=%s&img=%s">next</a>' % (gallery, _next(gallery, img, db)))
		l.append('</TD></TABLE></TD>')
	l.append('</TABLE>')
	l.append('<p>')
	l.append('<div align="center"><a href="../../__copy__" class="main_text"><b>© 2004 ecp</b></a><br>')
	l.append('<A HREF="./view_code" class="MAIN_TEXT">(view the gallery code)</a></div></html>')
	return '\n'.join(l)

def view_code():
	# a note ...
	# if you are viewing this code online, the replace functions will look like .replace('>', '>')
	# when in reality they look like .replace('>', '&gt;')
	# this is recursive, so the above line does not look like you are seeing either ;-)
	f = open(_path + 'gallery2.py', 'r')
	l = f.readlines()
	f.close()
	return '<HTML><PRE>\n%s\n</PRE></HTML>' % ''.join([s.replace('<', '<').replace('>', '>').replace('****', '****') for s in l])