diff --git a/include/class.client.php b/include/class.client.php
index e1057afa651472052589c0629fed129475d0e45e..8786c0e19cdb9719a86a556b3ce26795ac5ce62f 100644
--- a/include/class.client.php
+++ b/include/class.client.php
@@ -30,12 +30,12 @@ class Client {
     var $ht;
 
 
-    function Client($email,$id) {
+    function Client($id, $email=null) {
         $this->id =0;
         $this->load($id,$email);
     }
 
-    function load($id=0, $email='') {
+    function load($id=0, $email=null) {
 
         if(!$id && !($id=$this->getId()))
             return false;
@@ -115,8 +115,23 @@ class Client {
     }
 
     /* ------------- Static ---------------*/
-    function lookup($id, $email) {
+    function getLastTicketIdByEmail($email) {
+        $sql='SELECT ticketID FROM '.TICKET_TABLE
+            .' WHERE email='.db_input($email)
+            .' ORDER BY created '
+            .' LIMIT 1';
+        if(($res=db_query($sql)) && db_num_rows($res))
+            list($tid) = db_fetch_row($res);
+
+        return $tid;
+    }
+
+    function lookup($id, $email=null) {
         return ($id && is_numeric($id) && ($c=new Client($id,$email)) && $c->getId()==$id)?$c:null;
     }
+
+    function lookupByEmail($email) {
+        return (($id=self::getLastTicketIdByEmail($email)))?self::lookup($id, $email):null;
+    }
 }
 ?>
diff --git a/include/class.ticket.php b/include/class.ticket.php
index e887daae7d58ea040d13d72ed342f453fc801290..49ae031c44ca6ebdcd26c42d78c06dd929a62954 100644
--- a/include/class.ticket.php
+++ b/include/class.ticket.php
@@ -14,6 +14,7 @@
     vim: expandtab sw=4 ts=4 sts=4:
 **********************************************************************/
 include_once(INCLUDE_DIR.'class.staff.php');
+include_once(INCLUDE_DIR.'class.client.php');
 include_once(INCLUDE_DIR.'class.team.php');
 include_once(INCLUDE_DIR.'class.email.php');
 include_once(INCLUDE_DIR.'class.dept.php');
@@ -55,6 +56,7 @@ class Ticket{
     var $dept;  //Dept obj
     var $sla;   // SLA obj
     var $staff; //Staff obj
+    var $client; //Client Obj
     var $team;  //Team obj
     var $topic; //Topic obj
     var $tlock; //TicketLock obj
@@ -124,6 +126,7 @@ class Ticket{
         
         //Reset the sub classes (initiated ondemand)...good for reloads.
         $this->staff = null;
+        $this->client = null;
         $this->team  = null;
         $this->dept = null;
         $this->sla = null;
@@ -349,6 +352,14 @@ class Ticket{
 
         return $this->dept;
     }
+
+    function getClient() {
+
+        if(!$this->client)
+            $this->client = Client::lookup($this->getExtId(), $this->getEmail());
+
+        return $this->client;
+    }
     
     function getStaffId(){
         return $this->staff_id;
@@ -854,6 +865,43 @@ class Ticket{
         return true;
     }
 
+    function onOpenLimit($sendNotice=true) {
+        global $cfg;
+
+        //Log the limit notice as a warning for admin.
+        $msg=sprintf('Max open tickets (%d) reached  for %s ', $cfg->getMaxOpenTickets(), $this->getEmail());
+        sys::log(LOG_WARNING, 'Max. Open Tickets Limit ('.$this->getEmail().')', $msg);
+
+        if(!$sendNotice || !$cfg->sendOverlimitNotice()) return true;
+
+        //Send notice to user.
+        $dept = $this->getDept();
+                    
+        if(!$dept || !($tpl=$dept->getTemplate()))
+            $tpl=$cfg->getDefaultTemplate();
+            
+        if(!$dept || !($email=$dept->getAutoRespEmail()))
+            $email=$cfg->getDefaultEmail();
+
+        if($tpl && ($msg=$tpl->getOverlimitMsgTemplate()) && $email) {
+            $body=$this->replaceTemplateVars($msg['body']);
+            $subj=$this->replaceTemplateVars($msg['subj']);
+            $body = str_replace('%signature',($dept && $dept->isPublic())?$dept->getSignature():'',$body);
+            $email->send($this->getEmail(), $subj, $body);
+        }
+
+        $client= $this->getClient();
+        
+        //Alert admin...this might be spammy (no option to disable)...but it is helpful..I think.
+        $msg='Max. open tickets reached for '.$this->getEmail()."\n"
+            .'Open ticket: '.$client->getNumOpenTickets()."\n"
+            .'Max Allowed: '.$cfg->getMaxOpenTickets()."\n\nNotice sent to the user.";
+            
+        Sys::alertAdmin('Overlimit Notice',$msg);
+       
+        return true;
+    }
+
     function onResponse(){
         db_query('UPDATE '.TICKET_TABLE.' SET isanswered=1,lastresponse=NOW(), updated=NOW() WHERE ticket_id='.db_input($this->getId()));
     }
@@ -1708,16 +1756,33 @@ class Ticket{
     /*
      * The mother of all functions...You break it you fix it!
      *
-     *  $autorespond and $alertstaff overwrites config info...
+     *  $autorespond and $alertstaff overwrites config settings...
      */      
-    function create($vars,&$errors, $origin, $autorespond=true, $alertstaff=true) {
+    function create($vars, &$errors, $origin, $autorespond=true, $alertstaff=true) {
         global $cfg,$thisclient,$_FILES;
 
-        //Make sure the email address is not banned
-        if ($vars['email'] && EmailFilter::isBanned($vars['email'])) {
-            $errors['err']='Ticket denied. Error #403';
-            Sys::log(LOG_WARNING,'Ticket denied','Banned email - '.$vars['email']);
-            return 0;
+        //Check for 403
+        if ($vars['email']  && Validator::is_email($vars['email'])) {
+
+            //Make sure the email address is not banned
+            if(EmailFilter::isBanned($vars['email'])) {
+                $errors['err']='Ticket denied. Error #403';
+                Sys::log(LOG_WARNING,'Ticket denied','Banned email - '.$vars['email']);
+                return 0;
+            }
+
+            //Make sure the open ticket limit hasn't been reached. (LOOP CONTROL)
+            if($cfg->getMaxOpenTickets()>0 && strcasecmp($origin,'staff') 
+                    && ($client=Client::lookupByEmail($vars['email']))
+                    && ($openTickets=$client->getNumOpenTickets())
+                    && ($opentickets>=$cfg->getMaxOpenTickets()) ) {
+
+                $errors['err']="You've reached the maximum open tickets allowed.";
+                Sys::log(LOG_WARNING, 'Ticket denied -'.$vars['email'], 
+                        sprintf('Max open tickets (%d) reached for %s ', $cfg->getMaxOpenTickets(), $vars['email']));
+
+                return 0;
+            }
         }
         // Make sure email contents should not be rejected
         if (($email_filter=new EmailFilter($vars))
@@ -1777,15 +1842,6 @@ class Ticket{
                 $errors['duedate']='Due date must be in the future';
         }
 
-        //check attachment..if any is set ...only set on webbased tickets..
-        //XXX:?? Create ticket anyway and simply drop the attachments?? We're already doing so with emails.
-        if($_FILES['attachment']['name'] && $cfg->allowOnlineAttachments()) {
-            if(!$cfg->canUploadFileType($_FILES['attachment']['name']))
-                $errors['attachment']='Invalid file type [ '.Format::htmlchars($_FILES['attachment']['name']).' ]';
-            elseif($_FILES['attachment']['size']>$cfg->getMaxFileSize())
-                $errors['attachment']='File is too big. Max '.$cfg->getMaxFileSize().' bytes allowed';
-        }
-
         # Perform email filter actions on the new ticket arguments XXX: Move filter to the top and check for reject...
         if (!$errors && $email_filter) $email_filter->apply($vars);
 
@@ -1793,41 +1849,6 @@ class Ticket{
         # function
         if (isset($vars['autorespond'])) $autorespond=$vars['autorespond'];
 
-        //check ticket limits..if limit set is >0 
-        //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()) {
-                $errors['err']="You've reached the maximum open tickets allowed.";
-                //Send the notice only once (when the limit is reached) incase of autoresponders at client end.
-                if($cfg->getMaxOpenTickets()==$openTickets && $cfg->sendOverlimitNotice()) {
-                    if($vars['deptId'])
-                        $dept =Dept::lookup($vars['deptId']);
-                    
-                    if(!$dept || !($tpl=$dept->getTemplate()))
-                        $tpl=$cfg->getDefaultTemplate();
-
-                    if(!$dept || !($email=$dept->getAutoRespEmail()))
-                        $email=$cfg->getDefaultEmail();
-
-                    if($tpl && ($msg=$tpl->getOverlimitMsgTemplate()) && $email) {
-                        $body = str_replace('%name', $vars['name'],$msg['body']);
-                        $body = str_replace('%email',$vars['email'],$msg['body']);
-                        $body = str_replace('%url', $cfg->getBaseUrl(),$body);
-                        $body = str_replace('%signature',($dept && $dept->isPublic())?$dept->getSignature():'',$body);
-                        $email->send($vars['email'],$msg['subj'],$body);
-                    }
-                    
-                    //Log + Alert admin...this might be spammy (no option to disable)...but it is helpful..I think.
-                    $msg='Support ticket request denied for '.$vars['email']."\n".
-                         'Open ticket:'.$openTickets."\n".
-                         'Max Allowed:'.$cfg->getMaxOpenTickets()."\n\nNotice only sent once";
-                    Sys::log(LOG_CRIT,'Overlimit Notice',$msg);
-                }
-            }
-        }
-
         //Any error above is fatal.
         if($errors)  return 0;
         
@@ -1932,6 +1953,15 @@ class Ticket{
 
         $ticket->onNewTicket($vars['message'], $autorespond, $alertstaff);
 
+        /************ check if the user JUST reached the max. open tickets limit **********/
+        if($cfg->getMaxOpenTickets()>0
+                    && ($client=$ticket->getClient())
+                    && ($client->getNumOpenTickets()==$cfg->getMaxOpenTickets())) {
+            $ticket->onOpenLimit(($autorespond && strcasecmp($origin, 'staff')));
+        }
+
+        /* Phew! ... time for tea (KETEPA) */
+
         return $ticket;
     }
 
diff --git a/include/class.usersession.php b/include/class.usersession.php
index 9a8283e3741a9b97f59a06649293831108634f93..c12f3a0d8aaf70988cbe2c022c8346b3eccdeccd 100644
--- a/include/class.usersession.php
+++ b/include/class.usersession.php
@@ -107,8 +107,8 @@ class ClientSession extends Client {
     
     var $session;
 
-    function ClientSession($email,$id){
-        parent::Client($email,$id);
+    function ClientSession($email, $id){
+        parent::Client($id, $email);
         $this->session= new UserSession($email);
     }
 
diff --git a/setup/inc/sql/osticket-v1.7-mysql.sql b/setup/inc/sql/osticket-v1.7-mysql.sql
index a9966d536dd99e68378bc163e02da729b066352c..26ccd03522a5f700f33dae77e39bce6b146cc698 100644
--- a/setup/inc/sql/osticket-v1.7-mysql.sql
+++ b/setup/inc/sql/osticket-v1.7-mysql.sql
@@ -311,8 +311,9 @@ CREATE TABLE `%TABLE_PREFIX%email_template` (
   FULLTEXT KEY `message_subj` (`ticket_reply_subj`)
 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
 
+-- TODO: Dump revised copy before release!!!
 INSERT INTO `%TABLE_PREFIX%email_template` (`tpl_id`, `cfg_id`, `isactive`, `name`, `notes`, `ticket_autoresp_subj`, `ticket_autoresp_body`, `ticket_notice_subj`, `ticket_notice_body`, `ticket_alert_subj`, `ticket_alert_body`, `message_autoresp_subj`, `message_autoresp_body`, `message_alert_subj`, `message_alert_body`, `note_alert_subj`, `note_alert_body`, `assigned_alert_subj`, `assigned_alert_body`, `transfer_alert_subj`, `transfer_alert_body`, `ticket_overdue_subj`, `ticket_overdue_body`, `ticket_overlimit_subj`, `ticket_overlimit_body`, `ticket_reply_subj`, `ticket_reply_body`, `created`, `updated`) VALUES
-(1, 1, 1, 'osTicket Default Template', 'Default osTicket templates', 'Support Ticket Opened [#%ticket]', '%name,\r\n\r\nA request for support has been created and assigned ticket #%ticket. A representative will follow-up with you as soon as possible.\r\n\r\nYou can view this ticket''s progress online here: %url/view.php?e=%email&t=%ticket.\r\n\r\nIf you wish to send additional comments or information regarding this issue, please don''t open a new ticket. Simply login using the link above and update the ticket.\r\n\r\n%signature', '[#%ticket] %subject', '%name,\r\n\r\nOur customer care team has created a ticket, #%ticket on your behalf, with the following message.\r\n\r\n%message\r\n\r\nIf you wish to provide additional comments or information regarding this issue, please don''t open a new ticket. You can update or view this ticket''s progress online here: %url/view.php?e=%email&t=%ticket.\r\n\r\n%signature', 'New Ticket Alert', '%staff,\r\n\r\nNew ticket #%ticket created.\r\n-------------------\r\nName: %name\r\nEmail: %email\r\nDept: %dept\r\n\r\n%message\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', '[#%ticket] Message Added', '%name,\r\n\r\nYour reply to support request #%ticket has been noted.\r\n\r\nYou can view this support request progress online here: %url/view.php?e=%email&t=%ticket.\r\n\r\n%signature', 'New Message Alert', '%staff,\r\n\r\nNew message appended to ticket #%ticket\r\n\r\n----------------------\r\nName: %name\r\nEmail: %email\r\nDept: %dept\r\n\r\n%message\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', 'New Internal Note Alert', '%staff,\r\n\r\nInternal note appended to ticket #%ticket\r\n\r\n----------------------\r\nName: %name\r\n\r\n%note\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', 'Ticket #%ticket Assigned to you', '%assignee,\r\n\r\n%assigner has assigned ticket #%ticket to you or one of your teams!\r\n\r\n%note\r\n\r\nTo view complete details, simply login to the support system.\r\n\r\n%url/scp/tickets.php?id=%id\r\n\r\n- Your friendly Support Ticket System - powered by osTicket.', 'Ticket Transfer #%ticket - %dept', '%staff,\r\n\r\nTicket #%ticket has been transferred to %dept department\r\n\r\n----------------------\r\n\r\n%note\r\n\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n%url/scp/ticket.php?id=%id\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', 'Stale Ticket Alert', '%staff,\r\n\r\nA ticket, #%ticket assigned to you or in your department is seriously overdue.\r\n\r\n%url/scp/tickets.php?id=%id\r\n\r\nWe should all work hard to guarantee that all tickets are being addressed in a timely manner. Enough baby talk...please address the issue or you will hear from me again.\r\n\r\n\r\n- Your friendly (although with limited patience) Support Ticket System - powered by osTicket.', 'Support Ticket Denied', '%name\r\n\r\nNo support ticket has been created. You''ve exceeded maximum number of open tickets allowed.\r\n\r\nThis is a temporary block. To be able to open another ticket, one of your pending tickets must be closed. To update or add comments to an open ticket simply login using the link below.\r\n\r\n%url/view.php?e=%email\r\n\r\nThank you.\r\n\r\nSupport Ticket System', '[#%ticket] %subject', '%name,\r\n\r\nA customer support staff member has replied to your support request, #%ticket with the following response:\r\n\r\n%response\r\n\r\nWe hope this response has sufficiently answered your questions. If not, please do not send another email. Instead, reply to this email or login to your account for a complete archive of all your support requests and responses.\r\n\r\n%url/view.php?e=%email&t=%ticket\r\n\r\n%signature', '2011-08-05 17:00:03', '2012-03-19 01:44:54');
+(1, 1, 1, 'osTicket Default Template', 'Default osTicket templates', 'Support Ticket Opened [#%ticket]', '%name,\r\n\r\nA request for support has been created and assigned ticket #%ticket. A representative will follow-up with you as soon as possible.\r\n\r\nYou can view this ticket''s progress online here: %url/view.php?e=%email&t=%ticket.\r\n\r\nIf you wish to send additional comments or information regarding this issue, please don''t open a new ticket. Simply login using the link above and update the ticket.\r\n\r\n%signature', '[#%ticket] %subject', '%name,\r\n\r\nOur customer care team has created a ticket, #%ticket on your behalf, with the following message.\r\n\r\n%message\r\n\r\nIf you wish to provide additional comments or information regarding this issue, please don''t open a new ticket. You can update or view this ticket''s progress online here: %url/view.php?e=%email&t=%ticket.\r\n\r\n%signature', 'New Ticket Alert', '%staff,\r\n\r\nNew ticket #%ticket created.\r\n-------------------\r\nName: %name\r\nEmail: %email\r\nDept: %dept\r\n\r\n%message\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', '[#%ticket] Message Added', '%name,\r\n\r\nYour reply to support request #%ticket has been noted.\r\n\r\nYou can view this support request progress online here: %url/view.php?e=%email&t=%ticket.\r\n\r\n%signature', 'New Message Alert', '%staff,\r\n\r\nNew message appended to ticket #%ticket\r\n\r\n----------------------\r\nName: %name\r\nEmail: %email\r\nDept: %dept\r\n\r\n%message\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', 'New Internal Note Alert', '%staff,\r\n\r\nInternal note appended to ticket #%ticket\r\n\r\n----------------------\r\nName: %name\r\n\r\n%note\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', 'Ticket #%ticket Assigned to you', '%assignee,\r\n\r\n%assigner has assigned ticket #%ticket to you or one of your teams!\r\n\r\n%note\r\n\r\nTo view complete details, simply login to the support system.\r\n\r\n%url/scp/tickets.php?id=%id\r\n\r\n- Your friendly Support Ticket System - powered by osTicket.', 'Ticket Transfer #%ticket - %dept', '%staff,\r\n\r\nTicket #%ticket has been transferred to %dept department\r\n\r\n----------------------\r\n\r\n%note\r\n\r\n-------------------\r\n\r\nTo view/respond to the ticket, please login to the support ticket system.\r\n\r\n%url/scp/ticket.php?id=%id\r\n\r\n- Your friendly Customer Support System - powered by osTicket.', 'Stale Ticket Alert', '%staff,\r\n\r\nA ticket, #%ticket assigned to you or in your department is seriously overdue.\r\n\r\n%url/scp/tickets.php?id=%id\r\n\r\nWe should all work hard to guarantee that all tickets are being addressed in a timely manner. Enough baby talk...please address the issue or you will hear from me again.\r\n\r\n\r\n- Your friendly (although with limited patience) Support Ticket System - powered by osTicket.', 'Open Tickets Limit Reached', '%name\r\n\r\nYou've reached the maximum number of open tickets allowed.\r\n\r\nTo be able to open another ticket, one of your pending tickets must be closed. To update or add comments to an open ticket simply login using the link below.\r\n\r\n%url/view.php?e=%email\r\n\r\nThank you.\r\n\r\nSupport Ticket System', '[#%ticket] %subject', '%name,\r\n\r\nA customer support staff member has replied to your support request, #%ticket with the following response:\r\n\r\n%response\r\n\r\nWe hope this response has sufficiently answered your questions. If not, please do not send another email. Instead, reply to this email or login to your account for a complete archive of all your support requests and responses.\r\n\r\n%url/view.php?e=%email&t=%ticket\r\n\r\n%signature', '2011-08-05 17:00:03', '2012-03-19 01:44:54');
 
 DROP TABLE IF EXISTS `%TABLE_PREFIX%file`;
 CREATE TABLE `%TABLE_PREFIX%file` (