#!/usr/local/bin/python
import cgi
import cgitb 
import urllib
from berry411 import *
from geoparser import * 
from mysoup import *

def do_page():
    print "Content-Type: text/html\n\n<title>Job Search</title>"

    form = cgi.FieldStorage()

    near = form.getvalue("near", "")

    if len(near) > 0:
        csz = "%s,%s" % parseAddress(near)
    else:
        csz = ""

    query = form.getvalue("q", "")

    if len(query)==0:
        print '''
        <form method="get">
        Job Keywords: <input type="text" name="q"> <br>
        Where: <input type="text" name="near"> 
        <input type="submit" value="Search Jobs">
        </form><br>
        <h3>Popular Searches</h3>
        '''

        categories = ['Accounting', 'Aerospace', 'Engineering', 'Human Resources', 'Legal', 'Manufacturing', 'Media', 'Nursing', 'Recruitment', 'Sales', 'Secretarial', 'Travel']

        for query in categories:
            print '<a href="jobs.py?q=%(query)s&near=%(csz)s&">%(query)s</a><br>' % (locals())

        return

    page = int(form.getvalue("p", 1))
    searchurl = 'http://www.workzoo.com/ns?rpp=10&q=%s&l=%s&sb=Search+Jobs&d=7&r=15&s=b&xml=1&p=%d' % (urllib.quote_plus(query), urllib.quote_plus(csz), page)
    data = fetchurl(searchurl)
    soup = MySoup(data)

    totalPages = int(soup.response.totalpages.string)

    response = soup.response
    print """<META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="-1">"""
    
    print ''''%s' %s<br>
    Results %s - %s out of %s <hr>''' % (query, len(csz)>0 and ('in ' + csz) or '', response.resultfrom, response.resultto, response.totaljobs)
    for job in response.fetch('job'):
        print '<b><a href="%s">%s</a></b><br>' % (skweeze("http://www.workzoo.com" + job.joblink.string), job.title.string)

        print  '%s, %s miles' % (job.primarycity.string, int(float(job.primarycitydistance.string) + 0.5))
        
        print '<blockquote><font size=-1>"%s"</font></blockquote>' % job.snippet.string
        print '<font color="green">Arrived %s ago from <a href="%s">%s</a></font><br>' % (job.arrived.string, skweeze(job.jobsitelink.string), job.jobsitename.string)
        print '<hr>'


    if page > 1:
        print '<a href="%s">Prev</a>' % ("jobs.py?" + urllib.urlencode({'q': query, 'near': near, 'p': page-1}))
        if page+1 < totalPages:
            print ' | '
        
    if page+1 < totalPages:
        print '<a href="%s">Next</a>' % ("jobs.py?" + urllib.urlencode({'q': query, 'near': near, 'p': page+1}))
        
if __name__=="__main__":
    do_page()


