diff --git a/assets/default/css/theme.css b/assets/default/css/theme.css
index dde40189e88227edaa3f1c18e4aec6b7e1bb67db..c6a6242df3d461805e06d366f451d3abf34a29ff 100644
--- a/assets/default/css/theme.css
+++ b/assets/default/css/theme.css
@@ -495,7 +495,7 @@ body {
 #ticketForm div.error label, #clientLogin div.error label {
   color: #a00;
 }
-#ticketForm p, #clientLogin p {
+#clientLogin p {
   clear: both;
   text-align: center;
 }
@@ -646,7 +646,7 @@ a.refresh {
 #ticketThread table th {
   text-align: left;
   border-bottom: 1px solid #aaa;
-  font-size: 11pt;
+  font-size: 12px;
   padding: 5px;
 }
 #ticketThread table td {
@@ -659,7 +659,7 @@ a.refresh {
   background: #ddd;
 }
 #ticketThread .info {
-  padding: 5px;
+  padding: 2px;
   background: #f9f9f9;
   border-top: 1px solid #ddd;
   height: 16px;
@@ -667,16 +667,13 @@ a.refresh {
 }
 #ticketThread .info a {
   display: inline-block;
-  margin: 5px 20px 5px 0;
+  margin: 5px 10px 5px 0;
   padding-left: 24px;
   height: 16px;
   line-height: 16px;
   background-position: 0 50%;
   background-repeat: no-repeat;
 }
-#ticketThread .info .pdf {
-  background-image: url('../images/filetypes/pdf.png?1319636863');
-}
 
 #reply {
   margin-top: 20px;
diff --git a/attachment.php b/attachment.php
index 2446f2dc517c52ec3f08f5219a7a7c28114eacbb..819ff5863b559522f70a65fd1c2fc56846e37d8a 100644
--- a/attachment.php
+++ b/attachment.php
@@ -15,57 +15,22 @@
     vim: expandtab sw=4 ts=4 sts=4:
 **********************************************************************/
 require('secure.inc.php');
-//TODO: alert admin on any error on this file.
-if(!$thisclient || !$thisclient->isClient() || !$_GET['id'] || !$_GET['ref']) die('Access Denied');
+require_once(INCLUDE_DIR.'class.attachment.php');
+//Basic checks
+if(!$thisclient 
+        || !$_GET['id'] 
+        || !$_GET['h']
+        || !($attachment=Attachment::lookup($_GET['id']))
+        || !($file=$attachment->getFile()))
+    die('Unknown attachment!');
+
+//Validate session access hash - we want to make sure the link is FRESH! and the user has access to the parent ticket!!
+$vhash=md5($attachment->getFileId().session_id().$file->getHash());
+if(strcasecmp(trim($_GET['h']),$vhash) 
+        || !($ticket=$attachment->getTicket()) 
+        || !$ticket->checkClientAccess($thisclient)) 
+    die('Unknown or invalid attachment');
+//Download the file..
+$file->download();
 
-$sql='SELECT attach_id,ref_id,ticket.ticket_id,ticketID,ticket.created,dept_id,file_name,file_key,email FROM '.TICKET_ATTACHMENT_TABLE.
-    ' LEFT JOIN '.TICKET_TABLE.' ticket USING(ticket_id) '.
-    ' WHERE attach_id='.db_input($_GET['id']);
-//valid ID??
-if(!($res=db_query($sql)) || !db_num_rows($res)) die('Invalid/unknown file');
-list($id,$refid,$tid,$extid,$date,$deptID,$filename,$key,$email)=db_fetch_row($res);
-
-//Still paranoid...:)...check the secret session based hash and email
-$hash=MD5($tid*$refid.session_id());
-if(!$_GET['ref'] || strcmp($hash,$_GET['ref']) || strcasecmp($thisclient->getEmail(),$email)) die('Access denied: Kwaheri');
-
-
-//see if the file actually exits.
-$month=date('my',strtotime("$date"));
-$file=rtrim($cfg->getUploadDir(),'/')."/$month/$key".'_'.$filename;
-if(!file_exists($file))
-    $file=rtrim($cfg->getUploadDir(),'/')."/$key".'_'.$filename;
-    
-if(!file_exists($file)) die('Invalid Attachment');
-
-$extension =substr($filename,-3);
-switch(strtolower($extension))
-{
-  case "pdf": $ctype="application/pdf"; break;
-  case "exe": $ctype="application/octet-stream"; break;
-  case "zip": $ctype="application/zip"; break;
-  case "doc": $ctype="application/msword"; break;
-  case "xls": $ctype="application/vnd.ms-excel"; break;
-  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
-  case "gif": $ctype="image/gif"; break;
-  case "png": $ctype="image/png"; break;
-  case "jpg": $ctype="image/jpg"; break;
-  default: $ctype="application/force-download";
-}
-header("Pragma: public");
-header("Expires: 0");
-header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
-header("Cache-Control: public"); 
-header("Content-Type: $ctype");
-$user_agent = strtolower ($_SERVER["HTTP_USER_AGENT"]);
-if ((is_integer(strpos($user_agent,"msie"))) && (is_integer(strpos($user_agent,"win")))) 
-{
-  header( "Content-Disposition: filename=".basename($filename).";" );
-} else {
-  header( "Content-Disposition: attachment; filename=".basename($filename).";" );
-}
-header("Content-Transfer-Encoding: binary");
-header("Content-Length: ".filesize($file));
-readfile($file);
-exit();
 ?>
diff --git a/client.inc.php b/client.inc.php
index 5461bd2f75246f57b710f74312eb45b9c4cfba9a..b714e93b44bd587f4d10a2f292b2d4890bc63a3f 100644
--- a/client.inc.php
+++ b/client.inc.php
@@ -51,7 +51,7 @@ require_once(INCLUDE_DIR.'class.dept.php');
 //clear some vars
 $errors=array();
 $msg='';
-$thisclient=null;
+$thisclient=$nav=null;
 //Make sure the user is valid..before doing anything else.
 if($_SESSION['_client']['userID'] && $_SESSION['_client']['key'])
     $thisclient = new ClientSession($_SESSION['_client']['userID'],$_SESSION['_client']['key']);
@@ -60,6 +60,8 @@ if($_SESSION['_client']['userID'] && $_SESSION['_client']['key'])
 if($thisclient && $thisclient->getId() && $thisclient->isValid()){
      $thisclient->refreshSession();
 }
+/* Client specific defaults */
+define('PAGE_LIMIT',DEFAULT_PAGE_LIMIT);
 
 $nav = new UserNav($thisclient, 'home');
 ?>
diff --git a/images/bg.gif b/images/bg.gif
deleted file mode 100644
index e20f31775822d9b0a7a01ddaf38cb1f48a60e6f2..0000000000000000000000000000000000000000
Binary files a/images/bg.gif and /dev/null differ
diff --git a/images/fibres.png b/images/fibres.png
deleted file mode 100644
index 7ad3ac27f71bdf17f637ffae3d86d36e24359764..0000000000000000000000000000000000000000
Binary files a/images/fibres.png and /dev/null differ
diff --git a/images/home.gif b/images/home.gif
deleted file mode 100644
index b25c0781dd0b8f66d4a9271b662061b54d7a9c4d..0000000000000000000000000000000000000000
Binary files a/images/home.gif and /dev/null differ
diff --git a/images/icons/attachment.gif b/images/icons/attachment.gif
deleted file mode 100644
index 4400e61e9812a3b2a070c89fc6fce7489c104e17..0000000000000000000000000000000000000000
Binary files a/images/icons/attachment.gif and /dev/null differ
diff --git a/images/icons/refresh.gif b/images/icons/refresh.gif
deleted file mode 100644
index 8268958a19e016741fffb8309b1174e548f5ce19..0000000000000000000000000000000000000000
Binary files a/images/icons/refresh.gif and /dev/null differ
diff --git a/images/icons/thread.gif b/images/icons/thread.gif
deleted file mode 100644
index bffd6b0b3cf5ce0cadfc38683ee7fb3fa0a5c82a..0000000000000000000000000000000000000000
Binary files a/images/icons/thread.gif and /dev/null differ
diff --git a/images/icons/ticket.gif b/images/icons/ticket.gif
deleted file mode 100644
index 4304ea7955091c46d9fe570faefc643773a5c1de..0000000000000000000000000000000000000000
Binary files a/images/icons/ticket.gif and /dev/null differ
diff --git a/images/icons/ticket_source_email.gif b/images/icons/ticket_source_email.gif
deleted file mode 100644
index 6b57605d47b7fc2e4729b5a6602bdf4768ad749f..0000000000000000000000000000000000000000
Binary files a/images/icons/ticket_source_email.gif and /dev/null differ
diff --git a/images/icons/ticket_source_other.gif b/images/icons/ticket_source_other.gif
deleted file mode 100644
index 4304ea7955091c46d9fe570faefc643773a5c1de..0000000000000000000000000000000000000000
Binary files a/images/icons/ticket_source_other.gif and /dev/null differ
diff --git a/images/icons/ticket_source_phone.gif b/images/icons/ticket_source_phone.gif
deleted file mode 100644
index b9aa8ed58a2993eab69a1c83fba78bb627e9004f..0000000000000000000000000000000000000000
Binary files a/images/icons/ticket_source_phone.gif and /dev/null differ
diff --git a/images/icons/ticket_source_web.gif b/images/icons/ticket_source_web.gif
deleted file mode 100644
index 1b7a5b909075fb879056d15468e407df21e0507d..0000000000000000000000000000000000000000
Binary files a/images/icons/ticket_source_web.gif and /dev/null differ
diff --git a/images/lipsum.png b/images/lipsum.png
deleted file mode 100644
index feb6a95fba027cb3d54883fc64ade1294c74bd09..0000000000000000000000000000000000000000
Binary files a/images/lipsum.png and /dev/null differ
diff --git a/images/logo.png b/images/logo.png
deleted file mode 100644
index 256344139522f7f8bc65b36e1ef0890e0fa3cf52..0000000000000000000000000000000000000000
Binary files a/images/logo.png and /dev/null differ
diff --git a/images/logo2.jpg b/images/logo2.jpg
deleted file mode 100644
index 16bc12ed36e707ace9d2d9e5443cc6d3a895711b..0000000000000000000000000000000000000000
Binary files a/images/logo2.jpg and /dev/null differ
diff --git a/images/logout.gif b/images/logout.gif
deleted file mode 100644
index 6dd774f09e48292379250ac0f1be17ccdb30baec..0000000000000000000000000000000000000000
Binary files a/images/logout.gif and /dev/null differ
diff --git a/images/my_tickets.gif b/images/my_tickets.gif
deleted file mode 100644
index ee2d25bbedd01ba5a64e9a66f5fc72b7b876f10c..0000000000000000000000000000000000000000
Binary files a/images/my_tickets.gif and /dev/null differ
diff --git a/images/new_ticket.gif b/images/new_ticket.gif
deleted file mode 100644
index 32d9636e71fa848c3b7d0f0d8eb559b78465ef22..0000000000000000000000000000000000000000
Binary files a/images/new_ticket.gif and /dev/null differ
diff --git a/images/new_ticket_icon.jpg b/images/new_ticket_icon.jpg
deleted file mode 100644
index 855eef0644245185b7b2f700d35d6a953aa65cd1..0000000000000000000000000000000000000000
Binary files a/images/new_ticket_icon.jpg and /dev/null differ
diff --git a/images/poweredby.jpg b/images/poweredby.jpg
deleted file mode 100644
index c98eb7d679b09975599711643cfcd3549c0540f6..0000000000000000000000000000000000000000
Binary files a/images/poweredby.jpg and /dev/null differ
diff --git a/images/rainbow.png b/images/rainbow.png
deleted file mode 100644
index c08f52edb522e5ec42c237994622f3b8520b428b..0000000000000000000000000000000000000000
Binary files a/images/rainbow.png and /dev/null differ
diff --git a/images/refresh_btn.gif b/images/refresh_btn.gif
deleted file mode 100644
index 8a33b22d9a9b026391e38a8bbb0d6834eb789a93..0000000000000000000000000000000000000000
Binary files a/images/refresh_btn.gif and /dev/null differ
diff --git a/images/ticket_status.gif b/images/ticket_status.gif
deleted file mode 100644
index 0775549996b70c79816e455e6850d1abf0e376ab..0000000000000000000000000000000000000000
Binary files a/images/ticket_status.gif and /dev/null differ
diff --git a/images/ticket_status_icon.jpg b/images/ticket_status_icon.jpg
deleted file mode 100644
index bf27b1f904418c311f05b27f118a55622be51b47..0000000000000000000000000000000000000000
Binary files a/images/ticket_status_icon.jpg and /dev/null differ
diff --git a/images/verticalbar.jpg b/images/verticalbar.jpg
deleted file mode 100644
index 2678913d2cdb9b8ec861e71396fcb92a552ff13a..0000000000000000000000000000000000000000
Binary files a/images/verticalbar.jpg and /dev/null differ
diff --git a/images/view_closed_btn.gif b/images/view_closed_btn.gif
deleted file mode 100644
index 6cd8f080a9007a85a2c0f08a6133f54a0253d6e8..0000000000000000000000000000000000000000
Binary files a/images/view_closed_btn.gif and /dev/null differ
diff --git a/images/view_open_btn.gif b/images/view_open_btn.gif
deleted file mode 100644
index 8ed6be9ce8159b20abfb0c9ea69b5235a4903b33..0000000000000000000000000000000000000000
Binary files a/images/view_open_btn.gif and /dev/null differ
diff --git a/include/class.client.php b/include/class.client.php
index f7ede15c52fe33b0a1a99dfdecb8081c64407d0d..e1057afa651472052589c0629fed129475d0e45e 100644
--- a/include/class.client.php
+++ b/include/class.client.php
@@ -4,8 +4,8 @@
 
     Handles everything about client
 
-    The class will undergo major changes one client's accounts are used. 
-    At the moment we will play off the email + ticket ID authentication.
+    NOTE: Please note that osTicket uses email address and ticket ID to authenticate the user*!
+          Client is modeled on the info of the ticket used to login .
 
     Peter Rotich <peter@osticket.com>
     Copyright (c)  2006-2012 osTicket
@@ -19,75 +19,104 @@
 
 class Client {
 
-
     var $id;
     var $fullname;
     var $username;
-    var $passwd;
     var $email;
 
-    
-    var $udata;
     var $ticket_id;
     var $ticketID;
 
-    function Client($email,$id){
+    var $ht;
+
+
+    function Client($email,$id) {
         $this->id =0;
         $this->load($id,$email);
     }
 
-    function isClient(){
-        return TRUE;
-    }
+    function load($id=0, $email='') {
 
-    function load($id,$email=''){
+        if(!$id && !($id=$this->getId()))
+            return false;
 
-        $sql='SELECT ticket_id,ticketID,name,email FROM '.TICKET_TABLE.' WHERE ticketID='.db_input($id);
-        if($email){ //don't validate...using whatever is entered.
+        $sql='SELECT ticket_id, ticketID, name, email, phone, phone_ext '
+            .' FROM '.TICKET_TABLE
+            .' WHERE ticketID='.db_input($id);
+        if($email)
             $sql.=' AND email='.db_input($email);
-        }
-        $res=db_query($sql);
-        if(!$res || !db_num_rows($res))
+
+        if(!($res=db_query($sql)) || !db_num_rows($res))
             return NULL;
 
-        $row=db_fetch_array($res);
-        $this->udata=$row;
-        $this->id         = $row['ticketID']; //placeholder
-        $this->ticket_id  = $row['ticket_id'];
-        $this->ticketID   = $row['ticketID'];
-        $this->fullname   = ucfirst($row['name']);
-        $this->username   = $row['email'];
-        $this->email      = $row['email'];
+        $this->ht = db_fetch_array($res);
+        $this->id         = $this->ht['ticketID']; //placeholder
+        $this->ticket_id  = $this->ht['ticket_id'];
+        $this->ticketID   = $this->ht['ticketID'];
+        $this->fullname   = ucfirst($this->ht['name']);
+        $this->username   = $this->ht['email'];
+        $this->email      = $this->ht['email'];
+
+        $this->stats = array();
       
         return($this->id);
     }
 
+    function reload() {
+        return $this->load();
+    }
+
+    function isClient() {
+        return TRUE;
+    }
 
-    function getId(){
+    function getId() {
         return $this->id;
     }
 
-    function getEmail(){
+    function getEmail() {
         return $this->email;
     }
 
-    function getUserName(){
+    function getUserName() {
         return $this->username;
     }
 
-    function getName(){
+    function getName() {
         return $this->fullname;
     }
+
+    function getPhone() {
+        return $this->ht['phone'];
+    }
+
+    function getPhoneExt() {
+        return $this->ht['phone_ext'];
+    }
     
     function getTicketID() {
         return $this->ticketID;
     }
 
+    function getTicketStats() {
+
+        if(!$this->stats['tickets'])
+            $this->stats['tickets'] = Ticket::getClientStats($this->getEmail());
+
+        return $this->stats['tickets'];
+    }
+
+    function getNumTickets() {
+        return ($stats=$this->getTicketStats())?($stats['open']+$stats['closed']):0;
+    }
+
+    function getNumOpenTickets() {
+        return ($stats=$this->getTicketStats())?$stats['open']:0;
+    }
+
     /* ------------- Static ---------------*/
     function lookup($id, $email) {
         return ($id && is_numeric($id) && ($c=new Client($id,$email)) && $c->getId()==$id)?$c:null;
     }
-
 }
-
 ?>
diff --git a/include/class.config.php b/include/class.config.php
index 1e3d7745ffaf9788715308564bcc676fc28ac845..37040ebca4372e993870537bb248e9fb48685a5a 100644
--- a/include/class.config.php
+++ b/include/class.config.php
@@ -32,17 +32,20 @@ class Config {
         $this->load($id);
     }
 
-    function load($id) {
+    function load($id=0) {
+        if(!$id && !($id=$this->getId()))
+            return false;
 
-        $sql='SELECT * FROM '.CONFIG_TABLE.' WHERE id='.db_input($id);
-        if($id && ($res=db_query($sql)) && db_num_rows($res)) {
-            $this->config=db_fetch_array($res);
-            $this->id=$this->config['id'];
+        $sql='SELECT * FROM '.CONFIG_TABLE
+            .' WHERE id='.db_input($id);
+        if(!($res=db_query($sql)) || !db_num_rows($res))
+            return false;
 
-            return true;
-        }
+            
+        $this->config=db_fetch_array($res);
+        $this->id=$this->config['id'];
 
-        return false;
+        return true;
     }
 
     //Initialize some default values.
@@ -52,10 +55,13 @@ class Config {
     }
     
     function reload() {
-        if($this->load($this->id))
-            $this->init();
-    }
+        if(!$this->load($this->getId()))
+            return false;
+
+        $this->init();
 
+        return true;
+    }
 
     function isHelpDeskOffline() {
         return !$this->isSystemOnline();
@@ -75,7 +81,7 @@ class Config {
         return '1.7 DPR';
     }
 
-    function getSchemaVersion() {
+    function getSchemaSignature() {
         return $this->config['schema_signature'];
     }
 
@@ -111,7 +117,7 @@ class Config {
     }
 
     function getId() {
-        return $this->config['id'];
+        return $this->id;
     }
    
     function getTitle() {
@@ -145,6 +151,10 @@ class Config {
     function getPasswdResetPeriod() {
         return $this->config['passwd_reset_period'];
     }
+
+    function showRelatedTickets() {
+        return $this->config['show_related_tickets'];
+    }
         
     function getClientTimeout() {
         return $this->getClientSessionTimeout();
diff --git a/include/class.faq.php b/include/class.faq.php
index 99d6def270ef2f54340dda2cea0f9929a8712f5e..7e23803dc458272ed7f81184c190213ddabd0e85 100644
--- a/include/class.faq.php
+++ b/include/class.faq.php
@@ -192,7 +192,7 @@ class FAQ {
             /* The h key must match validation in file.php */
             $hash=$attachment['hash'].md5($attachment['id'].session_id().$attachment['hash']);
             if($attachment['size'])
-                $size=sprintf('(<i>%s</i>)',Format::file_size($attachment['size']));
+                $size=sprintf('&nbsp;<small>(<i>%s</i>)</small>',Format::file_size($attachment['size']));
 
             $str.=sprintf('<a class="Icon file" href="file.php?h=%s" target="%s">%s</a>%s&nbsp;%s',
                     $hash, $target, Format::htmlchars($attachment['name']), $size, $separator);
diff --git a/include/class.file.php b/include/class.file.php
index 91bd1cddce71f1438580bdffd9bf9782ffe125e9..b9bfbe1b7d2975ebdcc467bfb826ed35b8f1ec75 100644
--- a/include/class.file.php
+++ b/include/class.file.php
@@ -138,6 +138,7 @@ class AttachmentFile {
         exit();
     }
 
+    /* Function assumes the files types have been validated */
     function upload($file) {
         
         if(!$file['name'] || !is_uploaded_file($file['tmp_name']))
diff --git a/include/class.filter.php b/include/class.filter.php
index 9b9d7279052ad0e5624642cb9f9f1c2ed127a6c5..4f18e96514c307077b7300a02674f8ad1698039e 100644
--- a/include/class.filter.php
+++ b/include/class.filter.php
@@ -260,7 +260,7 @@ class Filter {
         #       Set owning department (?)
         if ($this->getDeptId())     $ticket['deptId']=$this->getDeptId();
         #       Set ticket priority (?)
-        if ($this->getPriorityId()) $ticket['pri']=$this->getPriorityId();
+        if ($this->getPriorityId()) $ticket['priorityId']=$this->getPriorityId();
         #       Set SLA plan (?)
         if ($this->getSLAId())      $ticket['slaId']=$this->getSLAId();
         #       Auto-assign to (?)
diff --git a/include/class.nav.php b/include/class.nav.php
index 561fc963dcd80165bc755fd96588907a3e06a1ac..a3b719f08d6bec16f6a2a7bb3fb264b1730c2f13 100644
--- a/include/class.nav.php
+++ b/include/class.nav.php
@@ -263,15 +263,24 @@ class UserNav {
 
             $navs = array();
             $user = $this->user;
-            $navs['home']=array('desc'=>'Support Center Home','href'=>'index.php','title'=>'');
+            $navs['home']=array('desc'=>'Support&nbsp;Center&nbsp;Home','href'=>'index.php','title'=>'');
             if($cfg && $cfg->isKnowledgebaseEnabled())
                 $navs['kb']=array('desc'=>'Knowledgebase','href'=>'kb/index.php','title'=>'');
 
-            $navs['new']=array('desc'=>'Open New Ticket','href'=>'open.php','title'=>'');
-            if($user && $user->isValid())
-                $navs['tickets']=array('desc'=>'My Tickets','href'=>'tickets.php','title'=>'');
-            else
+            $navs['new']=array('desc'=>'Open&nbsp;New&nbsp;Ticket','href'=>'open.php','title'=>'');
+            if($user && $user->isValid()) {
+                if($cfg && $cfg->showRelatedTickets()) {
+                    $navs['tickets']=array('desc'=>sprintf('My&nbsp;Tickets&nbsp;(%d)',$user->getNumTickets()),
+                                           'href'=>'tickets.php',
+                                            'title'=>'Show all tickets');
+                } else {
+                    $navs['tickets']=array('desc'=>'View&nbsp;Ticket&nbsp;Thread',
+                                           'href'=>sprintf('tickets.php?id=%d',$user->getTicketID()),
+                                           'title'=>'View ticket status');
+                }
+            } else {
                 $navs['status']=array('desc'=>'Check Ticket Status','href'=>'view.php','title'=>'');
+            }
             $this->navs=$navs;
         }
 
diff --git a/include/class.staff.php b/include/class.staff.php
index bfb0b79d2735c32b2410845fba1f0f89490bf0ba..9968965991fc024caa326747da423a01d0202eb8 100644
--- a/include/class.staff.php
+++ b/include/class.staff.php
@@ -37,15 +37,18 @@ class Staff {
         if(!$var && !($var=$this->getId()))
             return false;
 
-        $sql='SELECT staff.*,grp.*,tz.offset as tz_offset,TIME_TO_SEC(TIMEDIFF(NOW(),IFNULL(staff.passwdreset,staff.created))) as passwd_change_sec '.
-             'FROM '.STAFF_TABLE.' staff '.
-             'LEFT JOIN '.GROUP_TABLE.' grp ON(grp.group_id=staff.group_id) '.
-             'LEFT JOIN '.TIMEZONE_TABLE.' tz ON(tz.id=staff.timezone_id) ';
+        $sql='SELECT staff.*, grp.*, tz.offset as tz_offset '
+            .' ,TIME_TO_SEC(TIMEDIFF(NOW(),IFNULL(staff.passwdreset,staff.created))) as passwd_change_sec '
+            .' FROM '.STAFF_TABLE.' staff '
+            .' LEFT JOIN '.GROUP_TABLE.' grp ON(grp.group_id=staff.group_id) '
+            .' LEFT JOIN '.TIMEZONE_TABLE.' tz ON(tz.id=staff.timezone_id) ';
+
         $sql.=sprintf('WHERE %s=%s',is_numeric($var)?'staff_id':'username',db_input($var));
 
         if(!($res=db_query($sql)) || !db_num_rows($res))
             return NULL;
 
+        
         $this->ht=db_fetch_array($res);
         $this->id  = $this->ht['staff_id'];
         $this->teams =$this->ht['teams']=$this->getTeams();
diff --git a/include/class.ticket.php b/include/class.ticket.php
index 2c111cec2f5a733716c73d7c2a03402690f7ff10..4801f1625594d030dd137861cfb4e4db7d9896e9 100644
--- a/include/class.ticket.php
+++ b/include/class.ticket.php
@@ -175,6 +175,18 @@ class Ticket{
                  || $staff->getId()==$this->getStaffId());
     }
 
+    function checkClientAccess($client) {
+        global $cfg;
+
+        if(!is_object($client) && !($client=Client::lookup($client)))
+            return false;
+
+        if(!strcasecmp($client->getEmail(),$this->getEmail()))
+            return true;
+
+        return ($cfg && $cfg->showRelatedTickets() && $client->getTicketId()==$ticket->getExtId());
+    }
+
     //Getters
     function getId(){
         return  $this->id;
@@ -437,8 +449,10 @@ class Ticket{
 
     function getRelatedTicketsCount(){
 
-        $sql='SELECT count(*)  FROM '.TICKET_TABLE.' WHERE email='.db_input($this->getEmail());
-        return db_count($sql);
+        $sql='SELECT count(*)  FROM '.TICKET_TABLE
+            .' WHERE email='.db_input($this->getEmail());
+
+        return db_result(db_query($sql));
     }
 
     function getThreadCount() {
@@ -488,7 +502,7 @@ class Ticket{
                 ON (msg.ticket_id=attach.ticket_id AND msg.msg_id=attach.ref_id AND ref_type="M") '
             .' WHERE  msg.ticket_id='.db_input($this->getId())
             .' GROUP BY msg.msg_id '
-            .' ORDER BY msg.created DESC ';
+            .' ORDER BY msg.created ASC ';
 
         $messages=array();
         if(($res=db_query($sql)) && db_num_rows($res))
@@ -1193,7 +1207,9 @@ class Ticket{
 
         $this->onMessage($autorespond); //must be called b4 sending alerts to staff.
 
-        if(!($tpl = $dept->getTemplate()))
+        $dept = $this->getDept();
+
+        if(!$dept || !($tpl = $dept->getTemplate()))
             $tpl= $cfg->getDefaultTemplate();
 
         if(!($email=$cfg->getAlertEmail()))
@@ -1458,10 +1474,14 @@ class Ticket{
 
 
    
-    function lookup($id){ //Assuming local ID is the only lookup used!
+    function lookup($id) { //Assuming local ID is the only lookup used!
         return ($id && is_numeric($id) && ($ticket= new Ticket($id)) && $ticket->getId()==$id)?$ticket:null;    
     }
 
+    function lookupByExtId($id) {
+        return self::lookup(self:: getIdByExtId($id));
+    }
+
     function genExtRandID() {
         global $cfg;
 
@@ -1537,6 +1557,27 @@ class Ticket{
         return db_fetch_array(db_query($sql));
     }
 
+
+    /* Quick client's tickets stats 
+       @email - valid email. 
+     */
+    function getClientStats($email) {
+
+        if(!$email || !Validator::is_email($email))
+            return null;
+
+        $sql='SELECT count(open.ticket_id) as open, count(closed.ticket_id) as closed '
+            .' FROM '.TICKET_TABLE.' ticket '
+            .' LEFT JOIN '.TICKET_TABLE.' open
+                ON (open.ticket_id=ticket.ticket_id AND open.status=\'open\') '
+            .' LEFT JOIN '.TICKET_TABLE.' closed
+                ON (closed.ticket_id=ticket.ticket_id AND closed.status=\'closed\')'
+            .' WHERE ticket.email='.db_input($email);
+
+        return db_fetch_array(db_query($sql));
+    }
+
+    //FIXME: Refactor the code for version 1.7
     function update($var,&$errors) {
          global $cfg,$thisstaff;
 
@@ -1650,7 +1691,7 @@ class Ticket{
                 break;
             case 'staff':
                 $fields['deptId']   = array('type'=>'int',  'required'=>1, 'error'=>'Dept. required');
-                $fields['topicId']   = array('type'=>'int',  'required'=>1, 'error'=>'Topic required');
+                $fields['topicId']  = array('type'=>'int',  'required'=>1, 'error'=>'Topic required');
                 $fields['duedate']  = array('type'=>'date', 'required'=>0, 'error'=>'Invalid date - must be MM/DD/YY');
             case 'api':
                 $fields['source']   = array('type'=>'string', 'required'=>1, 'error'=>'Indicate source');
@@ -1660,10 +1701,10 @@ class Ticket{
                 break;
             default:
                 # TODO: Return error message
-                $errors['origin'] = 'Invalid origin given';
+                $errors['err']=$errors['origin'] = 'Invalid origin given';
         }
-        $fields['pri']      = array('type'=>'int',      'required'=>0, 'error'=>'Invalid Priority');
-        $fields['phone']    = array('type'=>'phone',    'required'=>0, 'error'=>'Valid phone # required');
+        $fields['priorityId']   = array('type'=>'int',      'required'=>0, 'error'=>'Invalid Priority');
+        $fields['phone']        = array('type'=>'phone',    'required'=>0, 'error'=>'Valid phone # required');
         
         if(!Validator::process($fields, $vars, $errors) && !$errors['err'])
             $errors['err'] ='Missing or invalid data - check the errors and try again';
@@ -1703,7 +1744,8 @@ class Ticket{
         if (isset($vars['autorespond'])) $autorespond=$vars['autorespond'];
 
         //check ticket limits..if limit set is >0 
-        //TODO: Base ticket limits on SLA... XXX: move it elsewhere??
+        //TODO:  XXX: move it elsewhere?? Client::checkMaxOpenTickets($email,$vars)
+
         if($vars['email'] && !$errors && $cfg->getMaxOpenTickets()>0 && strcasecmp($origin,'staff')){
             $openTickets=Ticket::getOpenTicketsByEmail($vars['email']);
             if($openTickets>=$cfg->getMaxOpenTickets()) {
@@ -1804,14 +1846,6 @@ class Ticket{
 
         //post the message.
         $msgid=$ticket->postMessage($vars['message'],$source,$vars['mid'],$vars['header'],true);
-        //TODO: recover from postMessage error??
-
-        //Upload attachments...web based. - XXX: Assumes user uploaded attachments!! XXX: move it to client interface.
-        if($_FILES['attachment']['name'] && $cfg->allowOnlineAttachments() && $msgid) {    
-            if(!$cfg->allowAttachmentsOnlogin() || ($cfg->allowAttachmentsOnlogin() && ($thisuser && $thisuser->isValid()))) {
-                $ticket->uploadAttachment($_FILES['attachment'],$msgid,'M');
-            }
-        }
 
         // Configure service-level-agreement for this ticket
         $ticket->selectSLAId($vars['slaId']);
diff --git a/include/class.topic.php b/include/class.topic.php
index 59159c8c90a5501150f22342fdf886ed5a729330..40ab8096bc1831b821ea37754b18e3d1a1a22e3e 100644
--- a/include/class.topic.php
+++ b/include/class.topic.php
@@ -135,6 +135,10 @@ class Topic {
         return $topics;
     }
 
+    function getPublicHelpTopics() {
+        return self::getHelpTopics(true);
+    }
+
 
     function getIdByName($topic){
         $sql='SELECT topic_id FROM '.TOPIC_TABLE.' WHERE topic='.db_input($topic);
diff --git a/include/client/header.inc.php b/include/client/header.inc.php
index ad88a0c80d13cb9655a5b113d28c5de94943b102..65966c838279f9174536bba87f01d5f5c3526cd4 100644
--- a/include/client/header.inc.php
+++ b/include/client/header.inc.php
@@ -21,8 +21,14 @@ header("Content-Type: text/html; charset=UTF-8\r\n");
             <a id="logo" href="<?php echo ROOT_PATH; ?>index.php" title="Support Center"><img src="<?php echo ASSETS_PATH; ?>images/logo.png" border=0 alt="Support Center"></a>
             <p>
              <?php
-             if($thisclient && is_object($thisclient) && $thisclient->isValid()) { ?>
-                <a href="<?php echo ROOT_PATH; ?>tickets.php">My Tickets</a> - 
+             if($thisclient && is_object($thisclient) && $thisclient->isValid()) { 
+                 echo $thisclient->getName().'&nbsp;-&nbsp;';
+                 ?>
+                <?php
+                if($cfg->showRelatedTickets()) {?>
+                <a href="<?php echo ROOT_PATH; ?>tickets.php">My Tickets <b>(<?php echo $thisclient->getNumTickets(); ?>)</b></a> - 
+                <?php
+                } ?>
                 <a href="<?php echo ROOT_PATH; ?>logout.php">Log Out</a>
              <?php 
              }elseif($nav){ ?>
diff --git a/include/client/kb-category.inc.php b/include/client/kb-category.inc.php
index f166fb5bdf8a1f528e56b965c5c32dca3e16dd8f..50a51782f214b8fc28b78f54afdd005c3f1a71df 100644
--- a/include/client/kb-category.inc.php
+++ b/include/client/kb-category.inc.php
@@ -1,34 +1,31 @@
 <?php
 if(!defined('OSTCLIENTINC') || !$category || !$category->isPublic()) die('Access Denied');
-
 ?>
-<div style="width:700;padding-top:10px; float:left;">
-  <h2>Frequently Asked Questions</h2>
-</div>
-<div style="float:right;text-align:right;padding-top:5px;padding-right:5px;">&nbsp;</div>
-<div class="clear"></div>
-<br>
-<div><strong><?php echo $category->getName() ?></strong></div>
+<h1><strong><?php echo $category->getName() ?></strong></h1>
 <p>
 <?php echo Format::safe_html($category->getDescription()); ?>
 </p>
 <hr>
 <?php
-$sql='SELECT faq.faq_id, question '
+$sql='SELECT faq.faq_id, question, count(attach.file_id) as attachments '
     .' FROM '.FAQ_TABLE.' faq '
     .' LEFT JOIN '.FAQ_ATTACHMENT_TABLE.' attach ON(attach.faq_id=faq.faq_id) '
     .' WHERE faq.ispublished=1 AND faq.category_id='.db_input($category->getId())
     .' GROUP BY faq.faq_id';
 if(($res=db_query($sql)) && db_num_rows($res)) {
-    echo '<div id="faq">
+    echo '
+         <h2>Frequently Asked Questions</h2>
+         <div id="faq">
             <ol>';
     while($row=db_fetch_array($res)) {
+        $attachments=$row['attachments']?'<span class="Icon file"></span>':'';
         echo sprintf('
-            <li><a href="faq.php?id=%d" >%s</a></li>',
-            $row['faq_id'],Format::htmlchars($row['question']));
+            <li><a href="faq.php?id=%d" >%s &nbsp;%s</a></li>',
+            $row['faq_id'],Format::htmlchars($row['question']), $attachments);
     }
     echo '  </ol>
-         </div>';
+         </div>
+         <p><a class="back" href="index.php">&laquo; Go Back</a></p>';
 }else {
     echo '<strong>Category does not have any FAQs. <a href="index.php">Back To Index</a></strong>';
 }
diff --git a/include/client/knowledgebase.inc.php b/include/client/knowledgebase.inc.php
index 0af99ba21b1d92532a6063e175e9cf0fdc69c2c9..83484e95de818d732a67fed39b980fd5e9262e95 100644
--- a/include/client/knowledgebase.inc.php
+++ b/include/client/knowledgebase.inc.php
@@ -1,5 +1,6 @@
 <?php
 if(!defined('OSTCLIENTINC')) die('Access Denied');
+
 ?>
 <h1>Frequently Asked Questions</h1>
 <form action="index.php" method="get" style="padding-top:15px;">
@@ -14,6 +15,7 @@ if(!defined('OSTCLIENTINC')) die('Access Denied');
                     $sql='SELECT category_id, name, count(faq.category_id) as faqs '
                         .' FROM '.FAQ_CATEGORY_TABLE.' cat '
                         .' LEFT JOIN '.FAQ_TABLE.' faq USING(category_id) '
+                        .' WHERE cat.ispublic=1 AND faq.ispublished=1 '
                         .' GROUP BY cat.category_id '
                         .' HAVING faqs>0 '
                         .' ORDER BY cat.name DESC ';
@@ -40,6 +42,7 @@ if(!defined('OSTCLIENTINC')) die('Access Denied');
                     $sql='SELECT ht.topic_id, ht.topic, count(faq.topic_id) as faqs '
                         .' FROM '.TOPIC_TABLE.' ht '
                         .' LEFT JOIN '.FAQ_TOPIC_TABLE.' faq USING(topic_id) '
+                        .' WHERE ht.ispublic=1 '
                         .' GROUP BY ht.topic_id '
                         .' HAVING faqs>0 '
                         .' ORDER BY ht.topic DESC ';
@@ -88,7 +91,7 @@ if($_REQUEST['q'] || $_REQUEST['cid'] || $_REQUEST['topicId']) { //Search.
 } else { //Category Listing.
     $sql='SELECT cat.category_id, cat.name, cat.description, cat.ispublic, count(faq.faq_id) as faqs '
         .' FROM '.FAQ_CATEGORY_TABLE.' cat '
-        .' LEFT JOIN '.FAQ_TABLE.' faq ON(faq.category_id=cat.category_id) '
+        .' LEFT JOIN '.FAQ_TABLE.' faq ON(faq.category_id=cat.category_id AND faq.ispublished=1) '
         .' WHERE cat.ispublic=1 '
         .' GROUP BY cat.category_id '
         .' HAVING faqs>0 '
diff --git a/include/client/open.inc.php b/include/client/open.inc.php
index fd31bc9b81f907204134114e1aed59d3fc728cb6..9c2a82b4706e1fc83253471eea8224e47cd7b382 100644
--- a/include/client/open.inc.php
+++ b/include/client/open.inc.php
@@ -1,21 +1,40 @@
 <?php
-if(!defined('OSTCLIENTINC')) die('Access Denied'); //Say bye to our friend..
+if(!defined('OSTCLIENTINC')) die('Access Denied!');
+$info=array();
+if($thisclient && $thisclient->isValid()) {
+    $info=array('name'=>$thisclient->getName(),
+                'email'=>$thisclient->getEmail(),
+                'phone'=>$thisclient->getPhone(),
+                'phone_ext'=>$thisclient->getPhoneExt());
+}
 
-$info=($_POST && $errors)?Format::htmlchars($_POST):array();
+$info=($_POST && $errors)?Format::htmlchars($_POST):$info;
 ?>
-
 <h1>Open a New Ticket</h1>
 <p>Please fill in the form below to open a new ticket.</p>
 <form id="ticketForm" method="post" action="open.php" enctype="multipart/form-data">
+    <input type="hidden" name="a" value="open">
     <div>
         <label for="name" class="required">Full Name:</label>
+        <?php
+        if($thisclient && $thisclient->isValid()) {
+            echo $thisclient->getName();
+        } else { ?>
         <input id="name" type="text" name="name" size="30" value="<?php echo $info['name']; ?>">
         <font class="error">*&nbsp;<?php echo $errors['name']; ?></font>
+        <?php
+        } ?>
     </div>
     <div>
-        <label for="email" class="required">E-Mail Address:</label>
+        <label for="email" class="required">Email Address:</label>
+        <?php
+        if($thisclient && $thisclient->isValid()) { 
+            echo $thisclient->getEmail();
+        } else { ?>
         <input id="email" type="text" name="email" size="30" value="<?php echo $info['email']; ?>">
         <font class="error">*&nbsp;<?php echo $errors['email']; ?></font>
+        <?php
+        } ?>
     </div>
     <div>
         <label for="phone">Telephone:</label>
@@ -30,16 +49,14 @@ $info=($_POST && $errors)?Format::htmlchars($_POST):array();
         <select id="topicId" name="topicId">
             <option value="" selected="selected">&mdash; Select a Help Topics &mdash;</option>
             <?php
-                $sql='SELECT topic_id,topic FROM '.TOPIC_TABLE.' WHERE isactive=1 ORDER BY topic';
-                 if(($res=db_query($sql)) && db_num_rows($res)) {
-                     while (list($topicId,$topic) = db_fetch_row($res)){
-                        $selected = ($info['topicId']==$topicId)?'selected="selected"':''; ?>
-                        <option value="<?php echo $topicId; ?>"<?php echo $selected; ?>><?php echo $topic; ?></option>
-                        <?php
-                     }
-                 }else{ ?>
-                    <option value="0" >General Inquiry</option>
-                <?php } ?>
+            if($topics=Topic::getPublicHelpTopics()) {
+                foreach($topics as $id =>$name) {
+                    echo sprintf('<option value="%d" %s>%s</option>',
+                            $id, ($info['topicId']==$id)?'selected="selected"':'', $name);
+                }
+            } else { ?>
+                <option value="0" >General Inquiry</option>
+            <?php } ?>
         </select>
         <font class="error">*&nbsp;<?php echo $errors['topicId']; ?></font>
     </div>
@@ -58,35 +75,41 @@ $info=($_POST && $errors)?Format::htmlchars($_POST):array();
         <textarea id="message" cols="60" rows="8" name="message"><?php echo $info['message']; ?></textarea>
     </div>
     <?php if(($cfg->allowOnlineAttachments() && !$cfg->allowAttachmentsOnlogin())
-            || ($cfg->allowAttachmentsOnlogin() && ($thisuser && $thisuser->isValid()))) { ?>
+            || ($cfg->allowAttachmentsOnlogin() && ($thisclient && $thisclient->isValid()))) { ?>
      <div>
-        <label for="attachment">Attachments:</label>
-        <input id="attachment" type="file" name="attachment"><font class="error">&nbsp;<?php echo $errors['attachment']; ?></font>
+        <label for="attachments">Attachments:</label>
+        <span id="uploads"></span>
+        <input type="file" class="multifile" name="attachments[]" id="attachments" size="30" value="" />
+        <font class="error">&nbsp;<?php echo $errors['attachments']; ?></font>
     </div>                                                                
     <?php } ?>
     <?php
-    if($cfg && $cfg->allowPriorityChange()) {
-      $sql='SELECT priority_id,priority_desc FROM '.TICKET_PRIORITY_TABLE.' WHERE ispublic=1 ORDER BY priority_urgency DESC';
-      if(($res=db_query($sql)) && db_num_rows($res)) {?>
-      <div>
+    if($cfg->allowPriorityChange() && ($priorities=Priority::getPriorities())) { ?>
+    <div>
         <label for="priority">Ticket Priority:</label>
         <select id="priority" name="priorityId">
-              <?php
+            <?php
                 if(!$info['priorityId'])
-                    $info['priorityId']=$cfg->getDefaultPriorityId(); //use system's default priority.
-                while($row=db_fetch_array($res)){ 
-                    $selected=$info['priorityId']==$row['priority_id']?'selected="selected"':'';
-                    ?>
-                    <option value="<?php echo $row['priority_id']; ?>" <?php echo $selected; ?> ><?php echo $row['priority_desc']; ?></option>
-              <?php } ?>
+                    $info['priorityId'] = $cfg->getDefaultPriorityId(); //System default.
+                foreach($priorities as $id =>$name) {
+                    echo sprintf('<option value="%d" %s>%s</option>',
+                                    $id, ($info['priorityId']==$id)?'selected="selected"':'', $name);
+                        
+                }
+            ?>
+
+                
+                
         </select>
+        
         <font class="error">&nbsp;<?php echo $errors['priorityId']; ?></font>
-     </div>
+        
+    </div>
     <?php
-      }
-    } ?>
+    }
+    ?>
     <?php
-    if($cfg && $cfg->enableCaptcha() && (!$thisuser || !$thisuser->isValid())) {
+    if($cfg && $cfg->enableCaptcha() && (!$thisclient || !$thisclient->isValid())) {
         if($_POST && $errors && !$errors['captcha'])
             $errors['captcha']='Please re-enter the text again';
         ?>
@@ -101,7 +124,7 @@ $info=($_POST && $errors)?Format::htmlchars($_POST):array();
     <?php
     } ?>
     <br>
-    <p>
+    <p style="padding-left:150px;">
         <input type="submit" value="Create Ticket">
         <input type="reset" value="Reset">
         <input type="button" value="Cancel" onClick='window.location.href="index.php"'>
diff --git a/include/client/tickets.inc.php b/include/client/tickets.inc.php
new file mode 100644
index 0000000000000000000000000000000000000000..a360217167bde83dedcb4decb339677e3c5370d6
--- /dev/null
+++ b/include/client/tickets.inc.php
@@ -0,0 +1,172 @@
+<?php
+if(!defined('OSTCLIENTINC') || !is_object($thisclient) || !$thisclient->isValid() || !$cfg->showRelatedTickets()) die('Access Denied');
+
+$qstr='&'; //Query string collector
+$status=null;
+if(isset($_REQUEST['status'])) { //Query string status has nothing to do with the real status used below.
+    $qstr.='status='.urlencode($_REQUEST['status']);
+    //Status we are actually going to use on the query...making sure it is clean!
+    switch(strtolower($_REQUEST['status'])) {
+     case 'open':
+     case 'closed':
+        $status=strtolower($_REQUEST['status']);
+        break;
+     default:
+        $status=''; //ignore
+    }
+} elseif($thisclient->getNumOpenTickets()) {
+    $status='open'; //Defaulting to open
+}
+
+$sortOptions=array('id'=>'ticketID', 'name'=>'ticket.name', 'subject'=>'ticket.subject',
+                    'email'=>'ticket.email', 'status'=>'ticket.status', 'dept'=>'dept_name','date'=>'ticket.created');
+$orderWays=array('DESC'=>'DESC','ASC'=>'ASC');
+//Sorting options...
+$order_by=$order=null;
+$sort=($_REQUEST['sort'] && $sortOptions[strtolower($_REQUEST['sort'])])?strtolower($_REQUEST['sort']):'date';
+if($sort && $sortOptions[$sort])
+    $order_by =$sortOptions[$sort];
+
+$order_by=$order_by?$order_by:'ticket_created';
+if($_REQUEST['order'] && $orderWays[strtoupper($_REQUEST['order'])]) 
+    $order=$orderWays[strtoupper($_REQUEST['order'])];
+
+$order=$order?$order:'ASC';
+if($order_by && strpos($order_by,','))
+    $order_by=str_replace(','," $order,",$order_by);
+
+$x=$sort.'_sort';
+$$x=' class="'.strtolower($order).'" ';
+
+$qselect='SELECT ticket.ticket_id,ticket.ticketID,ticket.dept_id,isanswered, dept.ispublic, ticket.subject, ticket.name, ticket.email '.
+           ',dept_name,ticket. status, ticket.source, ticket.created ';
+
+$qfrom='FROM '.TICKET_TABLE.' ticket '
+      .' LEFT JOIN '.DEPT_TABLE.' dept ON (ticket.dept_id=dept.dept_id) ';
+
+$qwhere =' WHERE ticket.email='.db_input($thisclient->getEmail());
+
+if($status){
+    $qwhere.=' AND ticket.status='.db_input($status);
+}
+
+$search=($_REQUEST['a']=='search' && $_REQUEST['q']);
+if($search) {
+    $qstr.='&a='.urlencode($_REQUEST['a']).'&q='.urlencode($_REQUEST['q']);
+    if(is_numeric($_REQUEST['q'])) {
+        $qwhere.=" AND ticket.ticketID LIKE '$queryterm%'";
+    } else {//Deep search!
+        $queryterm=db_real_escape($_REQUEST['q'],false); //escape the term ONLY...no quotes.
+        $qwhere.=' AND ( '
+                ." ticket.subject LIKE '%$queryterm%'"
+                ." OR message.message LIKE '%$queryterm%'"
+                ." OR response.response LIKE '%$queryterm%'"
+                .' ) ';
+        $deep_search=true;
+        //Joins needed for search
+        $qfrom.=' LEFT JOIN '.TICKET_MESSAGE_TABLE.' message ON (ticket.ticket_id=message.ticket_id )'
+               .' LEFT JOIN '.TICKET_RESPONSE_TABLE.' response ON (ticket.ticket_id=response.ticket_id )';
+    }
+}
+
+$total=db_count('SELECT count(DISTINCT ticket.ticket_id) '.$qfrom.' '.$qwhere);
+$pageNav=new Pagenate($total,$page, PAGE_LIMIT);
+$pageNav->setURL('tickets.php',$qstr.'&sort='.urlencode($_REQUEST['sort']).'&order='.urlencode($_REQUEST['order']));
+
+//more stuff...
+$qselect.=' ,count(attach_id) as attachments ';
+$qfrom.=' LEFT JOIN '.TICKET_ATTACHMENT_TABLE.' attach ON  ticket.ticket_id=attach.ticket_id ';
+$qgroup=' GROUP BY ticket.ticket_id';
+
+$query="$qselect $qfrom $qwhere $qgroup ORDER BY $order_by $order LIMIT ".$pageNav->getStart().",".$pageNav->getLimit();
+//echo $query;
+$res = db_query($query);
+$showing=($res && db_num_rows($res))?$pageNav->showing():"";
+$showing.=($status)?(' '.ucfirst($status).' Tickets'):' All Tickets';
+if($search)
+    $showing="Search Results: $showing";
+
+$negorder=$order=='DESC'?'ASC':'DESC'; //Negate the sorting
+
+?>
+<h1>My Tickets</h1>
+<br>
+<form action="tickets.php" method="get" id="ticketSearchForm">
+    <input type="hidden" name="a"  value="search">
+    <input type="text" name="q" size="20" value="<?php echo Format::htmlchars($_REQUEST['q']); ?>">
+    <select name="status">
+        <option value="">&mdash; Any Status &mdash;</option>
+        <option value="open" <?php echo ($status=='open')?'selected="selected"':'';?>>Open</option>
+        <option value="closed" <?php echo ($status=='closed')?'selected="selected"':'';?>>Closed</option>
+    </select>
+    <input type="submit" value="Go">
+</form>
+<a class="refresh" href="<?php echo $_SERVER['REQUEST_URI']; ?>">Refresh</a>
+<table id="ticketTable" width="800" border="0" cellspacing="0" cellpadding="0">
+    <caption><?php echo $showing; ?></caption>
+    <thead>
+        <tr>
+            <th width="70" nowrap>
+                <a href="tickets.php?sort=ID&order=<?php echo $negorder; ?><?php echo $qstr; ?>" title="Sort By Ticket ID">Ticket #</a>
+            </th>
+            <th width="100">
+                <a href="tickets.php?sort=date&order=<?php echo $negorder; ?><?php echo $qstr; ?>" title="Sort By Date">Create Date</a>
+            </th>
+            <th width="80">
+                <a href="tickets.php?sort=status&order=<?php echo $negorder; ?><?php echo $qstr; ?>" title="Sort By Status">Status</a>
+            </th>
+            <th width="240">
+                <a href="tickets.php?sort=subj&order=<?php echo $negorder; ?><?php echo $qstr; ?>" title="Sort By Subject">Subject</a>
+            </th>
+            <th width="150">
+                <a href="tickets.php?sort=dept&order=<?php echo $negorder; ?><?php echo $qstr; ?>" title="Sort By Department">Department</a>
+            </th>
+            <th width="150">Phone Number</th>
+        </tr>
+    </thead>
+    <tbody>
+    <?php
+     if($res && ($num=db_num_rows($res))) {
+        $defaultDept=Dept::getDefaultDeptName(); //Default public dept.
+        while ($row = db_fetch_array($res)) {
+            $dept=$row['ispublic']?$row['dept_name']:$defaultDept;
+            $subject=Format::htmlchars(Format::truncate($row['subject'],40));
+            if($row['attachments'])
+                $subject.='  &nbsp;&nbsp;<span class="Icon file"></span>';
+
+            $ticketID=$row['ticketID'];
+            if($row['isanswered'] && !strcasecmp($row['status'],'open')) {
+                $subject="<b>$subject</b>";
+                $ticketID="<b>$ticketID</b>";
+            }
+            $phone=Format::phone($row['phone']);
+            if($row['phone_ext'])
+                $phone.=' '.$row['phone_ext'];
+            ?>
+            <tr id="<?php echo $row['ticketID']; ?>">
+                <td class="centered">
+                <a class="Icon <?php echo strtolower($row['source']); ?>Ticket" title="<?php echo $row['email']; ?>" 
+                    href="tickets.php?id=<?php echo $row['ticketID']; ?>"><?php echo $ticketID; ?></a>
+                </td>
+                <td>&nbsp;<?=Format::db_date($row['created'])?></td>
+                <td>&nbsp;<?=ucfirst($row['status'])?></td>
+                <td>
+                    <a href="tickets.php?id=<?php echo $row['ticketID']; ?>"><?php echo $subject; ?></a>
+                </td>
+                <td>&nbsp;<?=Format::truncate($dept,30)?></td>
+                <td><?php echo $phone; ?></td>
+            </tr>
+        <?php
+        }
+
+     } else {
+         echo '<tr><td colspan="7">Your query did not match any records</td></tr>';
+     }
+    ?>
+    </tbody>
+</table>
+<?php
+if($res && $num>0) { 
+    echo '<div>&nbsp;Page:'.$pageNav->getPageLinks().'&nbsp;</div>';
+}
+?>
diff --git a/include/client/view.inc.php b/include/client/view.inc.php
new file mode 100644
index 0000000000000000000000000000000000000000..e720ed96bffa58c5d7321e7fe2544c7829a86678
--- /dev/null
+++ b/include/client/view.inc.php
@@ -0,0 +1,157 @@
+<?php
+if(!defined('OSTCLIENTINC') || !$thisclient || !$ticket || !$ticket->checkClientAccess($thisclient)) die('Access Denied!');
+
+$info=($_POST && $errors)?Format::htmlchars($_POST):array();
+
+$dept = $ticket->getDept();
+//Making sure we don't leak out internal dept names
+if(!$dept || !$dept->isPublic())
+    $dept = $cfg->getDefaultDept();
+
+?>
+<table width="800" cellpadding="1" cellspacing="0" border="0" id="ticketInfo">
+    <tr>
+        <td colspan="2" width="100%">
+            <h1>
+                Ticket #<?php echo $ticket->getExtId(); ?> &nbsp;
+                <a href="view.php?id=<?php echo $ticket->getExtId(); ?>" title="Reload"><span class="Icon refresh">&nbsp;</span></a>
+            </h1>
+        </td>
+    </tr> 
+    <tr>
+        <td width="50%">   
+            <table class="infoTable" cellspacing="1" cellpadding="3" width="100%" border="0">
+                <tr>
+                    <th width="100">Ticket Status:</th>
+                    <td><?php echo ucfirst($ticket->getStatus()); ?></td>
+                </tr>
+                <tr>
+                    <th>Department:</th>
+                    <td><?php echo Format::htmlchars($dept->getName()); ?></td>
+                </tr>
+                <tr>
+                    <th>Create Date:</th>
+                    <td><?php echo Format::db_datetime($ticket->getCreateDate()); ?></td>
+                </tr>
+           </table>
+       </td>
+       <td width="50%">
+           <table class="infoTable" cellspacing="1" cellpadding="3" width="100%" border="0">
+               <tr>
+                   <th width="100">Name:</th>
+                   <td><?php echo ucfirst($ticket->getName()); ?></td>
+               </tr>
+               <tr>
+                   <th width="100">Email:</th>
+                   <td><?php echo Format::htmlchars($ticket->getEmail()); ?></td>
+               </tr>
+               <tr>
+                   <th>Phone:</th>
+                   <td><?php echo $ticket->getPhoneNumber(); ?></td>
+               </tr>
+            </table>
+       </td>
+    </tr>
+</table>
+<br>
+<h2>Subject:<?php echo Format::htmlchars($ticket->getSubject()); ?></h2>
+<br>
+<span class="Icon thread">Ticket Thread</span>
+<div id="ticketThread">
+<?php    
+if($ticket->getThreadCount() && ($messages = $ticket->getMessages())) {
+     
+    foreach($messages as $message) {?>
+    
+        <table class="message" cellspacing="0" cellpadding="1" width="800" border="0">
+        
+            <tr><th><?php echo Format::db_datetime($message['created']); ?></th></tr>
+            
+            <tr><td><?php echo Format::display($message['message']); ?></td></tr>
+            
+            <?php
+            
+            if($message['attachments'] && ($links=$ticket->getAttachmentsLinks($message['msg_id'],'M'))) { ?>
+            
+                <tr><td class="info"><?php echo $links; ?></td></tr>
+                
+            <?php
+            
+            } ?>
+            
+        </table>
+        <?php
+        if($message['responses'] && ($responses=$ticket->getResponses($message['msg_id']))) {
+           foreach($responses as $resp) {
+               $staff=$cfg->hideStaffName()?'staff':Format::htmlchars($resp['staff_name']);
+               ?>
+               <table class="response" cellspacing="0" cellpadding="1" width="100%" border="0">
+                <tr>
+                    <th><?php echo Format::db_datetime($resp['created']);?>&nbsp;-&nbsp;<?php echo $staff; ?></th>
+                </tr>
+                <tr><td><?php echo Format::display($resp['response']); ?></td></tr>
+                <?php
+                if($resp['attachments'] && ($links=$ticket->getAttachmentsLinks($resp['response_id'],'R'))) {?>
+                 <tr><td class="info"><?php echo $links; ?></td></tr>
+                <?php
+                 }?>
+                </table>
+            <?
+           }
+       }
+    }
+}
+?>
+</div>
+<div class="clear" style="padding-bottom:10px;"></div>
+<?php if($errors['err']) { ?>
+    <div id="msg_error"><?php echo $errors['err']; ?></div>
+<?php }elseif($msg) { ?>
+    <div id="msg_notice"><?php echo $msg; ?></div>
+<?php }elseif($warn) { ?>
+    <div id="msg_warning"><?php echo $warn; ?></div>
+<?php } ?>
+<form id="reply" action="tickets.php?id=<?php echo $ticket->getExtId(); ?>#reply" name="reply" method="post" enctype="multipart/form-data">
+    <h2>Post a Reply</h2>
+    <input type="hidden" name="id" value="<?php echo $ticket->getExtId(); ?>">
+    <input type="hidden" name="a" value="reply">
+    <table border="0" cellspacing="0" cellpadding="3" width="800">
+        <tr>
+            <td width="160">
+                <label>Message:</label>
+            </td>
+            <td width="640">
+                <?php
+                if($ticket->isClosed()) {
+                    $msg='<b>Ticket will be reopened on message post</b>';
+                } else {
+                    $msg='To best assist you, please be specific and detailed';
+                }
+                ?>
+                <span id="msg"><em><?php echo $msg; ?> </em></span><font class="error">*&nbsp;<?php echo $errors['message']; ?></font><br/>
+                <textarea name="message" id="message" cols="50" rows="9" wrap="soft"><?php echo $info['message']; ?></textarea>
+            </td>
+        </tr>
+        <?php
+        if($cfg->allowOnlineAttachments()) { ?>
+        <tr>
+            <td width="160">
+                <label for="attachment">Attachments:</label>
+            </td>
+            <td width="640" id="reply_form_attachments" class="attachments">
+                <div class="uploads">
+                </div>
+                <div class="file_input">
+                    <input type="file" name="attachments[]" size="30" value="" />
+                </div>
+            </td>
+        </tr>
+        <?php
+        } ?>
+    </table>
+    <p style="padding-left:165px;">
+        <input type="submit" value="Post Reply">
+        <input type="reset" value="Reset">
+        <input type="button" value="Cancel" onClick="history.go(-1)">
+    </p>
+</form>
diff --git a/include/staff/tickets.inc.php b/include/staff/tickets.inc.php
index ea3a59ced3f99ae51ac4e83855433f6d84395ea0..d0b27690e2cf138140c1707e1f3a92809493cc91 100644
--- a/include/staff/tickets.inc.php
+++ b/include/staff/tickets.inc.php
@@ -180,8 +180,8 @@ if(!$order_by && $showanswered) {
 }elseif(!$order_by && !strcasecmp($status,'closed')){
     $order_by='ticket.closed, ticket.created'; //No priority sorting for closed tickets.
 }
-$order_by =$order_by?$order_by:'priority_urgency,effective_date,ticket.created';
-$order=$order?$order:'DESC';
+$order_by =$order_by?$order_by:'priority_urgency, effective_date, ticket.created';
+$order=$order?$order:'ASC';
 
 if($order_by && strpos($order_by,','))
     $order_by=str_replace(','," $order,",$order_by);
@@ -351,7 +351,7 @@ $basic_display=!isset($_REQUEST['advance_search'])?true:false;
 <div class="clear"></div>
 <div style="margin-bottom:20px">
 <form action="tickets.php" method="POST" name='tickets' onSubmit="return checkbox_checker(this,1,0);">
- <a class="refresh" href="">Refresh</a>
+ <a class="refresh" href="<?php echo $_SERVER['REQUEST_URI']; ?>">Refresh</a>
  <input type="hidden" name="a" value="mass_process" >
  <input type="hidden" name="status" value="<?php echo $status; ?>" >
  <table class="list" border="0" cellspacing="1" cellpadding="2" width="940">
diff --git a/index.php b/index.php
index 95bdfa55dcfc5c13e4ba79f9ad97c1e7b188630b..ac4fe04a014455d083aacab299fdace3a045e529 100644
--- a/index.php
+++ b/index.php
@@ -26,7 +26,7 @@ require(CLIENTINC_DIR.'header.inc.php');
 
     <div id="new_ticket">
         <h3>Open A New Ticket</h3>
-        <form method="link" action="open.php">  
+        <form method="get" action="open.php">  
             <div>Please provide as much detail as possible so we can best assist you. To update a previously submitted ticket, please login.</div>
             <input type="submit" value="Open a New Ticket">
         </form>
@@ -34,7 +34,7 @@ require(CLIENTINC_DIR.'header.inc.php');
 
     <div id="check_status">
         <h3>Check Ticket Status</h3>
-        <form class="status_form" action="login.php" method="get">
+        <form class="status_form" action="view.php" method="get">
             <div>We provide archives and history of all your current and past support requests complete with responses.</div>
             <input type="submit" value="Check Ticket Status">
         </form>
@@ -44,9 +44,8 @@ require(CLIENTINC_DIR.'header.inc.php');
 <?php
 if($cfg && $cfg->isKnowledgebaseEnabled()){ 
     //FIXME: provide ability to feature or select random FAQs ??
-    ?>
-<br>
-Be pure to browse our <a href="kb/index.php">Frequently Asked Questions (FAQs)</a>, before opening a ticket.
+?>
+<p>Be sure to browse our <a href="kb/index.php">Frequently Asked Questions (FAQs)</a>, before opening a ticket.</p>
 </div>
 <?php
 } ?>
diff --git a/js/osticket.js b/js/osticket.js
index fd04ff48c809525267ebaacca85ac30cb37dd00a..a809e6f2f794a0534096c69b2a210428424d703d 100644
--- a/js/osticket.js
+++ b/js/osticket.js
@@ -1,79 +1 @@
-jQuery(function($) {
-    var max_uploads = 5;
-    var current_reply_uploads = 0;
-    var current_note_uploads = 0;
-
-    function parse_upload(elem) {
-        var new_input = elem.clone();
-        var filename = elem.val();
-        if(filename != '') {
-            var container = elem.parent().parent();
-            var form_type = container.attr('id');
-            elem.blur().hide();
-            $('.uploads', container).append('<div><label><input type="checkbox" name="uploads[]" value="' + filename + '" checked="checked"> ' + filename.replace('C:\\', '').replace('fakepath\\', '') + '</label></div>');
-            if(form_type=='reply_form_attachments') {
-                current_reply_uploads++;
-                if(current_reply_uploads < max_uploads) {
-                    elem.after(new_input.val('').blur());
-                } 
-            } else {
-                current_note_uploads++;
-                if(current_note_uploads < max_uploads) {
-                    elem.after(new_input.val('').blur());
-                } 
-            }
-        }
-    }
-
-    if($.browser.msie) {
-        $('.attachments').delegate('input[type=file]', 'click', function() {
-            var elem = $(this);
-            setTimeout(function() {
-                parse_upload(elem);
-                elem.blur();
-            }, 0);
-        });
-    } else {
-        $('.attachments').delegate('input[type=file]', 'change', function() {
-            var elem = $(this);
-            parse_upload(elem);
-        });
-    }
-
-    $('.uploads').delegate('.uploads input', 'click', function(e) {
-        e.preventDefault();
-        var elem = $(this);
-        elem.attr('checked', 'checked');
-        if(confirm("Are you sure you want to delete this attachment?")==true) {
-            var container = elem.parent().parent();
-            var cparent = container.parent().parent();
-            var form_type = cparent.attr('id');
-            var filename = elem.val();
-            $('input[type=file]', cparent).each(function() {
-                if($(this).val() == filename) {
-                    $(this).remove();
-                }
-            });
-            container.remove();
-            var new_input = $('input[type=file]:last', cparent).clone();
-            var last_elem = $('input[type=file]:last', cparent);
-            if(form_type=='reply_form_attachments') {
-                current_reply_uploads--;
-                if(current_reply_uploads < max_uploads) {
-                    if(last_elem.css('display')=='none') {
-                        last_elem.after(new_input.val('').show());
-                    }
-                } 
-            } else {
-                current_note_uploads--;
-                if(current_note_uploads < max_uploads) {
-                    if(last_elem.css('display')=='none') {
-                        last_elem.after(new_input.val('').show());
-                    }
-                } 
-            }
-        } else {
-            e.preventDefault();
-        }
-    });    
-});
\ No newline at end of file
+//Nothing for now...
diff --git a/login.php b/login.php
index 69a73c679951b0c7ec4ab30616eb08519aaaf828..044d74644785f32a0f79bae76e6c4309fd473b2a 100644
--- a/login.php
+++ b/login.php
@@ -1,6 +1,6 @@
 <?php
 /*********************************************************************
-    index.php
+    login.php
 
     Client Login 
 
@@ -41,9 +41,8 @@ if($_POST && (!empty($_POST['lemail']) && !empty($_POST['lticket']))):
         }
     }
     //See if we can fetch local ticket id associated with the ID given
-    if(!$errors && is_numeric($ticketID) && Validator::is_email($email) && ($tid=Ticket::getIdByExtId($ticketID))) {
+    if(!$errors && is_numeric($ticketID) && Validator::is_email($email) && ($ticket=Ticket::lookupByExtId($ticketID))) {
         //At this point we know the ticket is valid.
-        $ticket= new Ticket($tid);
         //TODO: 1) Check how old the ticket is...3 months max?? 2) Must be the latest 5 tickets?? 
         //Check the email given.
         if($ticket->getId() && strcasecmp($ticket->getEMail(),$email)==0){
@@ -61,7 +60,7 @@ if($_POST && (!empty($_POST['lemail']) && !empty($_POST['lticket']))):
             //Redirect tickets.php
             session_write_close();
             session_regenerate_id();
-            @header("Location: tickets.php");
+            @header("Location: tickets.php?id=".$ticket->getExtId());
             require_once('tickets.php'); //Just incase. of header already sent error.
             exit;
         }
diff --git a/open.php b/open.php
index a5d86d0776924c30768ac6bfea2889ee2c83052e..11d3a0a9d3397d64941886169a5fa2892ea663a1 100644
--- a/open.php
+++ b/open.php
@@ -19,22 +19,27 @@ $inc='open.inc.php';    //default include.
 $errors=array();
 if($_POST):
     $_POST['deptId']=$_POST['emailId']=0; //Just Making sure we don't accept crap...only topicId is expected.
-    if(!$thisuser && $cfg->enableCaptcha()){
+    if($thisclient) {
+        $_POST['name']=$thisclient->getName();
+        $_POST['email']=$thisclient->getEmail();
+    } elseif($cfg->enableCaptcha()) {
         if(!$_POST['captcha'])
             $errors['captcha']='Enter text shown on the image';
         elseif(strcmp($_SESSION['captcha'],md5($_POST['captcha'])))
             $errors['captcha']='Invalid - try again!';
     }
 
-    //FIXME: Allow logged in users to use diff email?
-    if($thisuser && strcasecmp($thisuser->getEmail(),$_POST['email']))
-        $errors['email']='Email mismatch.';
-
     //Ticket::create...checks for errors..
     if(($ticket=Ticket::create($_POST,$errors,SOURCE))){
         $msg='Support ticket request created';
-        if($thisclient && $thisclient->isValid()) //Logged in...simply view the newly created ticket.
+        //Logged in...simply view the newly created ticket.
+        if($thisclient && $thisclient->isValid()) {
+            if(!$cfg->showRelatedTickets())
+                $_SESSION['_client']['key']= $ticket->getExtId(); //Resetting login Key to the current ticket!
+            session_write_close();
+            session_regenerate_id();
             @header('Location: tickets.php?id='.$ticket->getExtId());
+        }
         //Thank the user and promise speedy resolution!
         $inc='thankyou.inc.php';
     }else{
diff --git a/secure.inc.php b/secure.inc.php
index f6664ab8174548983c9ddc9b8cb7d2436e2f2554..3096b3503036e8746a58cea56aa2e85f977b4896 100644
--- a/secure.inc.php
+++ b/secure.inc.php
@@ -13,7 +13,7 @@
 
     vim: expandtab sw=4 ts=4 sts=4:
 **********************************************************************/
-if(!strcasecmp(basename($_SERVER['SCRIPT_NAME']),basename(__FILE__))) die('Kwaheri rafiki!');
+if(!strcasecmp(basename($_SERVER['SCRIPT_NAME']),basename(__FILE__))) die('Kwaheri!');
 if(!file_exists('client.inc.php')) die('Fatal Error.');
 require_once('client.inc.php');
 //User must be logged in!
diff --git a/tickets.php b/tickets.php
index 072abef7de07d35112cbe2ff637bc254fd0d4455..d4759ba522e328911d2e9a494254ce338ea7f905 100644
--- a/tickets.php
+++ b/tickets.php
@@ -16,59 +16,57 @@
 **********************************************************************/
 require('secure.inc.php');
 if(!is_object($thisclient) || !$thisclient->isValid()) die('Access denied'); //Double check again.
-
 require_once(INCLUDE_DIR.'class.ticket.php');
 $ticket=null;
-$inc='tickets.inc.php'; //Default page...show all tickets.
-//Check if any id is given...
-if(($id=$_REQUEST['id']?$_REQUEST['id']:$_POST['ticket_id']) && is_numeric($id)) {
-    //id given fetch the ticket info and check perm.
-    $ticket= new Ticket(Ticket::getIdByExtId((int)$id));
-    if(!$ticket or !$ticket->getEmail()) {
-        $ticket=null; //clear.
-        $errors['err']='Access Denied. Possibly invalid ticket ID';
-    }elseif(strcasecmp($thisclient->getEmail(),$ticket->getEmail())){
-        $errors['err']='Security violation. Repeated violations will result in your account being locked.';
-        $ticket=null; //clear.
-    }else{
-        //Everything checked out.
-        $inc='viewticket.inc.php';
+if($_REQUEST['id']) {
+    if(!($ticket=Ticket::lookupByExtId($_REQUEST['id']))) {
+        $errors['err']='Unknown or invalid ticket ID.';
+    }elseif(!$ticket->checkClientAccess($thisclient)) {
+        $errors['err']='Unknown or invalid ticket ID.'; //Using generic message on purpose!
+        $ticket=null;
     }
 }
+
 //Process post...depends on $ticket object above.
 if($_POST && is_object($ticket) && $ticket->getId()):
     $errors=array();
     switch(strtolower($_POST['a'])){
-    case 'postmessage':
-        if(strcasecmp($thisclient->getEmail(),$ticket->getEmail())) { //double check perm again!
+    case 'reply':
+        if(!$ticket->checkClientAccess($thisclient)) //double check perm again!
             $errors['err']='Access Denied. Possibly invalid ticket ID';
-            $inc='tickets.inc.php'; //Show the tickets.               
-        }
 
         if(!$_POST['message'])
             $errors['message']='Message required';
+
         //check attachment..if any is set
-        if($_FILES['attachment']['name']) {
-            if(!$cfg->allowOnlineAttachments()) //Something wrong with the form...user shouldn't have an option to attach
-                $errors['attachment']='File [ '.$_FILES['attachment']['name'].' ] rejected';
-            elseif(!$cfg->canUploadFileType($_FILES['attachment']['name']))
-                $errors['attachment']='Invalid file type [ '.$_FILES['attachment']['name'].' ]';
-            elseif($_FILES['attachment']['size']>$cfg->getMaxFileSize())
-                $errors['attachment']='File is too big. Max '.$cfg->getMaxFileSize().' bytes allowed';
+        $files=($cfg->allowOnlineAttachments() && $_FILES['attachments'])?Format::files($_FILES['attachments']):array();
+        if($files) {
+
+            foreach($files as $file) {
+                if(!$file['name']) continue;
+
+                if(!$cfg->canUploadFileType($file['name']))
+                    $errors['attachment']='Invalid file type [ '.$file['name'].' ]';
+                elseif($file['size']>$cfg->getMaxFileSize())
+                    $errors['attachment']='File '.$file['name'].'is too big. Max '.$cfg->getMaxFileSize().' bytes allowed';
+            }
         }
                     
         if(!$errors){
             //Everything checked out...do the magic.
             if(($msgid=$ticket->postMessage($_POST['message'],'Web'))) {
-                if($_FILES['attachment']['name'] && $cfg->canUploadFiles() && $cfg->allowOnlineAttachments())
-                    $ticket->uploadAttachment($_FILES['attachment'],$msgid,'M');
-                    
+                if($files && $cfg->allowOnlineAttachments())
+                    $ticket->uploadAttachments($files,$msgid,'M');
+
                 $msg='Message Posted Successfully';
-            }else{
+            } else {
                 $errors['err']='Unable to post the message. Try again';
             }
-        }else{
-            $errors['err']=$errors['err']?$errors['err']:'Error(s) occured. Please try again';
+
+        } elseif(!$errors['err']) {
+            print_r($errors);
+            $errors['err']='Error(s) occurred. Please try again';
+           
         }
         break;
     default:
@@ -76,6 +74,15 @@ if($_POST && is_object($ticket) && $ticket->getId()):
     }
     $ticket->reload();
 endif;
+$nav->setActiveNav('tickets');
+if($ticket && $ticket->checkClientAccess($thisclient)) {
+    $inc='view.inc.php';
+} elseif($cfg->showRelatedTickets() && $thisclient->getNumTickets()) {
+    $inc='tickets.inc.php';
+} else {
+    $nav->setActiveNav('new');
+    $inc='open.inc.php';
+}
 include(CLIENTINC_DIR.'header.inc.php');
 include(CLIENTINC_DIR.$inc);
 include(CLIENTINC_DIR.'footer.inc.php');
diff --git a/view.php b/view.php
index b8be15b040948bfddd9ee2b31b3fe1bd60726ed2..984b04c3019645c6ca1d075bbab0aac8460e4094 100644
--- a/view.php
+++ b/view.php
@@ -1,4 +1,21 @@
 <?php
+/*********************************************************************
+    view.php
+
+    Ticket View.
+
+    Peter Rotich <peter@osticket.com>
+    Copyright (c)  2006-2010 osTicket
+    http://www.osticket.com
+
+    Released under the GNU General Public License WITHOUT ANY WARRANTY.
+    See LICENSE.TXT for details.
+
+    vim: expandtab sw=4 ts=4 sts=4:
+    $Id: $
+**********************************************************************/
+require('secure.inc.php');
+if(!is_object($thisclient) || !$thisclient->isValid()) die('Access denied'); //Double check again.
 //We are now using tickets.php but we need to keep view.php for backward compatibility
 require('tickets.php');
 ?>