#!/usr/bin/python
# -*- coding:cp1251 -*-

import cgi
import _mysql

print "Content-Type: text/html; charset=cp1251"
print ""

def who_is():
  if user_id==page_id:
    return "user"
  else:
    return "guest"

form = cgi.FieldStorage()
db=_mysql.connect(host="localhost", user="root", passwd="", db="citylife")
db.query("SET NAMES cp1251")


if "login" in form and "passwd" in form:
  login=form['login'].value
  passwd=form['passwd'].value
  query="SELECT * FROM users WHERE mail=\'%s\' AND parol=\'%s\'"%(login,passwd)
  db.query(query)
  data=db.store_result()
  user=data.fetch_row(1,1)  
  if len(user)==0:
    pass
  else:
    user=user[0]
    global user_id
    global page_id
    user_id=user.get('id')
    page_id=user_id
    
    
elif "user_id" in form and "page_id" in form:
  global user_id
  global page_id
  user_id=form["user_id"].value
  page_id=form["page_id"].value
  if who_is()=="user":
    db.query("SELECT * FROM users WHERE id=\'%s\'"%user_id)
  elif who_is()=="guest":
    db.query("SELECT * FROM users WHERE id=\'%s\'"%page_id)    
  data=db.store_result()
  user=data.fetch_row(1,1)
  if len(user)==0:
    print "<html><body><script type=\"text/javascript\">alert (\"Такого пользователя не существует\");document.location.href=\"/index.htm\"; </script></body></html>"  
  else:
    user=user[0]
else:
  print "<html><body><script type=\"text/javascript\">document.location.href=\"/index.htm\" </script></body></html>"

print "<html><head>"
if len(user)==0:
  pass
else:
  print "<title>%s %s</title>"%(user.get("name"),user.get("l_name")) 
print "<link rel=\"stylesheet\" href=\"/page.css\" type=\"text/css\" /></head><body>"
if len(user)==0:
  print "<script type=\"text/javascript\"> alert (\"Такого пользователя не существует\"); document.location.href=\"/index.htm\" </script>"
print "<div id=\"container\">"
if who_is()=="user":
  print "<div id=\"Horizontal\"><ul style=\"margin:0 250px\">"
  print   """
   <li class='active'><a href='#'><span>сообщения</span></a></li>
   <li class='active'><a href='#'><span>фото</span></a></li>
   <li class='active'><a href='#'><span>друзья</span></a></li>
   <li class='active'><a href='#'><span>настройки</span></a></li>
   <li class='active'><a href='#'><span>редактировать</span></a></li>"""
elif who_is()=="guest":
  print "<div id=\"Horizontal\"><ul style=\"margin:0 390px\">"
  print   """
   <li class='active'><a href='#'><span>%s %s</span></a></li>
   <li class='active'><a href='#'><span>фото</span></a></li>
   <li class='active'><a href='#'><span>друзья</span></a></li>
          """%(user.get('name'),user.get('l_name'))
print "</ul></div>"
print "*" 
print "<div id=\"left\"><div id=\"avatar\">"
if user.get('photo')=="":
  if who_is()=="user":
    print "<a href=\"#\"><img src=\"/CSS/images/ask_add.jpg\" /></a>"
  elif who_is()=="guest":
    print "<img src=\"/CSS/images/ask.jpg\" />"
else:
  print "<img src=\"%s\" />"%user.get('photo')
print "</div></div>"
print "</div>"
print "</body></html>"