diff --git a/include/ajax.tickets.php b/include/ajax.tickets.php
index ab44bd3e3e0ac39343c5425ccec2f612d90f4445..0506d24471843024c5e212434543335e6adfaf0a 100644
--- a/include/ajax.tickets.php
+++ b/include/ajax.tickets.php
@@ -21,38 +21,67 @@ include_once(INCLUDE_DIR.'class.ticket.php');
 class TicketsAjaxAPI extends AjaxController {
    
     function search() {
+        global $thisstaff;
+
+        if(!is_numeric($_REQUEST['q']))
+            return self::searchByEmail();
+
 
         $limit = isset($_REQUEST['limit']) ? (int) $_REQUEST['limit']:25;
-        $items=array();
+        $tickets=array();
 
         $sql='SELECT DISTINCT ticketID, email'
-            .' FROM '.TICKET_TABLE;
-
-        $emailSearch=false;
-        if(is_numeric($_REQUEST['q']))
-            $sql.=' WHERE ticketID LIKE \''.db_input($_REQUEST['q'], false).'%\'';
-        else {
-            $emailSearch=true;
-            $sql.=' WHERE email LIKE \'%'.db_input(strtolower($_REQUEST['q']), false).'%\' ';
+            .' FROM '.TICKET_TABLE
+            .' WHERE ticketID LIKE \''.db_input($_REQUEST['q'], false).'%\'';
+              
+        $sql.=' AND ( staff_id='.db_input($thisstaff->getId());
+            
+        if(($teams=$thisstaff->getTeams()) && count(array_filter($teams)))
+            $sql.=' OR team_id IN('.implode(',', array_filter($teams)).')';
+            
+        if(!$thisstaff->showAssignedOnly() && ($depts=$thisstaff->getDepts()))
+            $sql.=' OR dept_id IN ('.implode(',', $depts).')';
+
+        $sql.=' )  '
+            .' ORDER BY created  LIMIT '.$limit;
+
+        if(($res=db_query($sql)) && db_num_rows($res)) {
+            while(list($id, $email)=db_fetch_row($res))
+                $tickets[] = array('id'=>$id, 'email'=>$email, 'value'=>$id, 'info'=>"$id - $email");
         }
 
-        $sql.=' ORDER BY created  LIMIT '.$limit;
+        return $this->json_encode($tickets);
+    }
+
+    function searchByEmail() {
+        global $thisstaff;
+
+
+        $limit = isset($_REQUEST['limit']) ? (int) $_REQUEST['limit']:25;
+        $tickets=array();
 
+        $sql='SELECT email, count(ticket_id) as tickets '
+            .' FROM '.TICKET_TABLE
+            .' WHERE email LIKE \'%'.db_input(strtolower($_REQUEST['q']), false).'%\' ';
+                
+        $sql.=' AND ( staff_id='.db_input($thisstaff->getId());
+
+        if(($teams=$thisstaff->getTeams()) && count(array_filter($teams)))
+            $sql.=' OR team_id IN('.implode(',', array_filter($teams)).')';
+
+        if(!$thisstaff->showAssignedOnly() && ($depts=$thisstaff->getDepts()))
+            $sql.=' OR dept_id IN ('.implode(',', $depts).')';
+        
+        $sql.=' ) '
+            .' GROUP BY email '
+            .' ORDER BY created  LIMIT '.$limit;
+            
         if(($res=db_query($sql)) && db_num_rows($res)) {
-            while(list($id,$email,$name)=db_fetch_row($res)) {
-                if($emailSearch) {
-                    $info = "$email - $id";
-                    $value = $email;
-                } else {
-                    $info = "$id -$email";
-                    $value = $id;
-                }
-
-                $items[] = array('id'=>$id, 'email'=>$email, 'value'=>$value, 'info'=>$info);
-            }
+            while(list($email, $count)=db_fetch_row($res))
+                $tickets[] = array('email'=>$email, 'value'=>$email, 'info'=>"$email ($count)");
         }
 
-        return $this->json_encode($items);
+        return $this->json_encode($tickets);
     }
 
     function acquireLock($tid) {
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.sla.php b/include/class.sla.php
index cbd9aa43083643bdae20a9625207162b0c832f38..7055977a8a752408bf2671f6e87cd404f9f32409 100644
--- a/include/class.sla.php
+++ b/include/class.sla.php
@@ -74,6 +74,10 @@ class SLA {
         return (!$this->ht['disable_overdue_alerts']);
     }
 
+    function alertOnOverdue() {
+        return $this->sendAlerts();
+    }
+
     function priorityEscalation() {
         return ($this->ht['enable_priority_escalation']);
     }
diff --git a/include/class.staff.php b/include/class.staff.php
index 9968965991fc024caa326747da423a01d0202eb8..878c0333efc1cc5ad8416dba744c02ebc0c379f5 100644
--- a/include/class.staff.php
+++ b/include/class.staff.php
@@ -27,12 +27,12 @@ class Staff {
     var $teams;
     var $stats;
     
-    function Staff($var){
+    function Staff($var) {
         $this->id =0;
         return ($this->load($var));
     }
 
-    function load($var=''){
+    function load($var='') {
 
         if(!$var && !($var=$this->getId()))
             return false;
@@ -59,7 +59,7 @@ class Staff {
         return ($this->id);
     }
 
-    function reload(){
+    function reload() {
         return $this->load();
     }
 
@@ -67,15 +67,15 @@ class Staff {
         return $this->ht;
     }
 
-    function getInfo(){
+    function getInfo() {
         return $this->getHastable();
     }
 
     /*compares user password*/
-    function check_passwd($password){
+    function check_passwd($password) {
 
         /*bcrypt based password match*/
-        if(Passwd::cmp($password,$this->getPasswd()))
+        if(Passwd::cmp($password, $this->getPasswd()))
             return true;
 
         /*Fall back to MD5 && force a password reset if it matches*/
@@ -93,7 +93,7 @@ class Staff {
     }
 
     /* check if passwd reset is due. */
-    function isPasswdResetDue(){
+    function isPasswdResetDue() {
         global $cfg;
         return ($cfg && $cfg->getPasswdResetPeriod() && $this->ht['passwd_change_sec']>($cfg->getPasswdResetPeriod()*30*24*60*60));
     }
@@ -110,7 +110,7 @@ class Staff {
         return $this->ht['daylight_saving']?true:false;
     }
 
-    function getRefreshRate(){
+    function getRefreshRate() {
         return $this->ht['auto_refresh_rate'];
     }
 
@@ -118,39 +118,39 @@ class Staff {
         return $this->ht['max_page_size'];
     }
 
-    function getId(){
+    function getId() {
         return $this->id;
     }
 
-    function getEmail(){
+    function getEmail() {
         return $this->ht['email'];
     }
 
-    function getUserName(){
+    function getUserName() {
         return $this->ht['username'];
     }
 
-    function getPasswd(){
+    function getPasswd() {
         return $this->ht['passwd'];
     }
 
-    function getName(){
+    function getName() {
         return ucfirst($this->ht['firstname'].' '.$this->ht['lastname']);
     }
         
-    function getFirstName(){
+    function getFirstName() {
         return $this->ht['firstname'];
     }
         
-    function getLastName(){
+    function getLastName() {
         return $this->ht['lastname'];
     }
     
-    function getGroupId(){
+    function getGroupId() {
         return $this->ht['group_id'];
     }
 
-    function getSignature(){
+    function getSignature() {
         return $this->ht['signature'];
     }
 
@@ -158,24 +158,24 @@ class Staff {
         return $this->ht['default_signature_type'];
     }
 
-    function forcePasswdChange(){
+    function forcePasswdChange() {
         return ($this->ht['change_passwd']);
     }
 
-    function getDepts(){
+    function getDepts() {
         //Departments the user is allowed to access...based on the group they belong to + user's dept.
-        return array_filter(array_unique(array_merge(explode(',',$this->ht['dept_access']),array($this->dept_id)))); //Neptune help us
+        return array_filter(array_unique(array_merge(explode(',', $this->ht['dept_access']), array($this->dept_id)))); //Neptune help us
     }
 
     function getDepartments() {
         return $this->getDepts();
     }
 
-    function getDeptId(){
+    function getDeptId() {
         return $this->ht['dept_id'];
     }
 
-    function getDept(){
+    function getDept() {
 
         if(!$this->dept && $this->getDeptIf())
             $this->dept= Dept::lookup($this->getDeptId());
@@ -184,27 +184,27 @@ class Staff {
     }
 
 
-    function isManager(){
+    function isManager() {
         return (($dept=$this->getDept()) && $dept->getManagerId()==$this->getId());
     }
 
-    function isStaff(){
+    function isStaff() {
         return TRUE;
     }
 
-    function isGroupActive(){
+    function isGroupActive() {
         return ($this->ht['group_enabled']);
     }
 
-    function isactive(){
+    function isactive() {
         return ($this->ht['isactive']);
     }
 
-    function isVisible(){
+    function isVisible() {
          return ($this->ht['isvisible']);
     }
         
-    function onVacation(){
+    function onVacation() {
         return ($this->ht['onvacation']);
     }
 
@@ -212,35 +212,39 @@ class Staff {
         return ($this->isactive() && $this->isGroupActive() && !$this->onVacation());
     }
 
-    function isAccessLimited(){
+    function showAssignedOnly() {
         return ($this->ht['assigned_only']);
     }
+
+    function isAccessLimited() {
+        return $this->showAssignedOnly();
+    }
   
-    function isadmin(){
+    function isadmin() {
         return ($this->ht['isadmin']);
     }
 
     function isTeamMember($teamId) {
-        return ($teamId && in_array($teamId,$this->getTeams()));
+        return ($teamId && in_array($teamId, $this->getTeams()));
     }
 
     function canAccessDept($deptId) {
-        return ($deptId && in_array($deptId,$this->getDepts()) && !$this->isAccessLimited());
+        return ($deptId && in_array($deptId, $this->getDepts()) && !$this->isAccessLimited());
     }
 
-    function canCreateTickets(){
+    function canCreateTickets() {
         return ($this->ht['can_create_tickets']);
     }
 
-    function canEditTickets(){
+    function canEditTickets() {
         return ($this->ht['can_edit_tickets']);
     }
     
-    function canDeleteTickets(){
+    function canDeleteTickets() {
         return ($this->ht['can_delete_tickets']);
     }
    
-    function canCloseTickets(){
+    function canCloseTickets() {
         return ($this->ht['can_close_tickets']);
     }
 
@@ -256,13 +260,13 @@ class Staff {
         return ($this->ht['can_ban_emails']);
     }
   
-    function canManageTickets(){
+    function canManageTickets() {
         return ($this->isadmin() 
                  || $this->canDeleteTickets() 
                     || $this->canCloseTickets());
     }
 
-    function canManagePremade(){
+    function canManagePremade() {
         return ($this->ht['can_manage_premade']);
     }
 
@@ -270,7 +274,7 @@ class Staff {
         return $this->canManagePremade();
     }
 
-    function canManageFAQ(){
+    function canManageFAQ() {
         return ($this->ht['can_manage_faq']);
     }
 
@@ -278,15 +282,16 @@ class Staff {
         return $this->canManageFAQ();
     }
 
-    function showAssignedTickets(){
+    function showAssignedTickets() {
         return ($this->ht['show_assigned_tickets']
                 && ($this->isAdmin() || $this->isManager()));
     }
 
-    function getTeams(){
+    function getTeams() {
         
-        if(!$this->teams){
-            $sql='SELECT team_id FROM '.TEAM_MEMBER_TABLE.' WHERE staff_id='.db_input($this->getId());
+        if(!$this->teams) {
+            $sql='SELECT team_id FROM '.TEAM_MEMBER_TABLE
+                .' WHERE staff_id='.db_input($this->getId());
             if(($res=db_query($sql)) && db_num_rows($res))
                 while(list($id)=db_fetch_row($res))
                     $this->teams[] = $id;
@@ -310,7 +315,6 @@ class Staff {
     }
 
     function getNumAssignedTickets() {
-
         return ($stats=$this->getTicketsStats())?$stats['assigned']:0;
     }
 
@@ -319,7 +323,7 @@ class Staff {
     }
 
     //Staff profile update...unfortunately we have to separate it from admin update to avoid potential issues
-    function updateProfile($vars,&$errors){
+    function updateProfile($vars, &$errors) {
 
         $vars['firstname']=Format::striptags($vars['firstname']);
         $vars['lastname']=Format::striptags($vars['lastname']);
@@ -347,13 +351,13 @@ class Staff {
         if($vars['mobile'] && !Validator::is_phone($vars['mobile']))
             $errors['mobile']='Valid number required';
 
-        if($vars['passwd1'] || $vars['passwd2'] || $vars['cpasswd']){
+        if($vars['passwd1'] || $vars['passwd2'] || $vars['cpasswd']) {
 
             if(!$vars['passwd1'])
                 $errors['passwd1']='New password required';
             elseif($vars['passwd1'] && strlen($vars['passwd1'])<6)
                 $errors['passwd1']='Must be at least 6 characters';
-            elseif($vars['passwd1'] && strcmp($vars['passwd1'],$vars['passwd2']))
+            elseif($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2']))
                 $errors['passwd2']='Password(s) do not match';
             
             if(!$vars['cpasswd'])
@@ -387,7 +391,7 @@ class Staff {
 
 
         if($vars['passwd1'])
-            $sql.=',change_passwd=0,passwdreset=NOW(),passwd='.db_input(Passwd::hash($vars['passwd1']));
+            $sql.=' ,change_passwd=0, passwdreset=NOW(), passwd='.db_input(Passwd::hash($vars['passwd1']));
 
         $sql.=' WHERE staff_id='.db_input($this->getId());
 
@@ -397,25 +401,26 @@ class Staff {
     }
 
 
-    function updateTeams($teams){
+    function updateTeams($teams) {
 
-        if($teams){
-            foreach($teams as $k=>$id){
-                $sql='INSERT IGNORE INTO '.TEAM_MEMBER_TABLE.' SET updated=NOW(),staff_id='.db_input($this->getId()).',team_id='.db_input($id);
+        if($teams) {
+            foreach($teams as $k=>$id) {
+                $sql='INSERT IGNORE INTO '.TEAM_MEMBER_TABLE.' SET updated=NOW() '
+                    .' ,staff_id='.db_input($this->getId()).', team_id='.db_input($id);
                 db_query($sql);
             }
         }
         $sql='DELETE FROM '.TEAM_MEMBER_TABLE.' WHERE staff_id='.db_input($this->getId());
         if($teams)
-            $sql.=' AND team_id NOT IN('.implode(',',$teams).')';
+            $sql.=' AND team_id NOT IN('.implode(',', $teams).')';
         
         db_query($sql);
 
         return true;
     }
 
-    function update($vars,&$errors) {
-        if(!$this->save($this->getId(),$vars,$errors))
+    function update($vars, &$errors) {
+        if(!$this->save($this->getId(), $vars, $errors))
             return false;
 
         $this->updateTeams($vars['teams']);
@@ -424,14 +429,14 @@ class Staff {
         return true;
     }
 
-    function delete(){
+    function delete() {
         global $thisstaff;
 
         if(!$thisstaff || !($id=$this->getId()) || $id==$thisstaff->getId())
             return 0;
 
         $sql='DELETE FROM '.STAFF_TABLE.' WHERE staff_id='.db_input($id).' LIMIT 1';
-        if(db_query($sql) && ($num=db_affected_rows())){
+        if(db_query($sql) && ($num=db_affected_rows())) {
             // DO SOME HOUSE CLEANING
             //Move remove any ticket assignments...TODO: send alert to Dept. manager?
             db_query('UPDATE '.TICKET_TABLE.' SET staff_id=0 WHERE status=\'open\' AND staff_id='.db_input($id));
@@ -468,7 +473,7 @@ class Staff {
         return self::getStaffMembers(true);
     }
 
-    function getIdByUsername($username){
+    function getIdByUsername($username) {
 
         $sql='SELECT staff_id FROM '.STAFF_TABLE.' WHERE username='.db_input($username);
         if(($res=db_query($sql)) && db_num_rows($res))
@@ -476,7 +481,7 @@ class Staff {
 
         return $id;
     }
-    function getIdByEmail($email){
+    function getIdByEmail($email) {
                     
         $sql='SELECT staff_id FROM '.STAFF_TABLE.' WHERE email='.db_input($email);
         if(($res=db_query($sql)) && db_num_rows($res))
@@ -485,25 +490,25 @@ class Staff {
         return $id;
     }
 
-    function lookup($id){
+    function lookup($id) {
         return ($id && is_numeric($id) && ($staff= new Staff($id)) && $staff->getId()==$id)?$staff:null;
     }
 
-    function login($username,$passwd,&$errors,$strike=true){
+    function login($username, $passwd, &$errors, $strike=true) {
         global $cfg;
 
 
         if($_SESSION['_staff']['laststrike']) {
             if((time()-$_SESSION['_staff']['laststrike'])<$cfg->getStaffLoginTimeout()) {
                 $errors['err']='You\'ve reached maximum failed login attempts allowed.';
-            }else{ //Timeout is over.
+            } else { //Timeout is over.
                 //Reset the counter for next round of attempts after the timeout.
                 $_SESSION['_staff']['laststrike']=null;
                 $_SESSION['_staff']['strikes']=0;
             }
         }
    
-        if(!$errors && ($user=new StaffSession($username)) && $user->getId() && $user->check_passwd($passwd)){
+        if(!$errors && ($user=new StaffSession($username)) && $user->getId() && $user->check_passwd($passwd)) {
             //update last login && password reset stuff.
             $sql='UPDATE '.STAFF_TABLE.' SET lastlogin=NOW() ';
             if($user->isPasswdResetDue() && !$user->isAdmin())
@@ -516,7 +521,7 @@ class Staff {
             $user->refreshSession(); //set the hash.
             $_SESSION['TZ_OFFSET']=$user->getTZoffset();
             $_SESSION['daylight']=$user->observeDaylight();
-            Sys::log(LOG_DEBUG,'Staff login',sprintf("%s logged in [%s]",$user->getUserName(),$_SERVER['REMOTE_ADDR'])); //Debug.
+            Sys::log(LOG_DEBUG,'Staff login',sprintf("%s logged in [%s]", $user->getUserName(), $_SERVER['REMOTE_ADDR'])); //Debug.
             $sid=session_id(); //Current ID
             session_regenerate_id(TRUE);
             //Destroy old session ID - needed for PHP version < 5.1.0 TODO: remove when we move to php 5.3 as min. requirement.
@@ -535,25 +540,25 @@ class Staff {
             $alert='Excessive login attempts by a staff member?'."\n".
                    'Username: '.$_POST['username']."\n".'IP: '.$_SERVER['REMOTE_ADDR']."\n".'TIME: '.date('M j, Y, g:i a T')."\n\n".
                    'Attempts #'.$_SESSION['_staff']['strikes']."\n".'Timeout: '.($cfg->getStaffLoginTimeout()/60)." minutes \n\n";
-            Sys::log(LOG_ALERT,'Excessive login attempts ('.$_POST['username'].')',$alert,($cfg->alertONLoginError()));
+            Sys::log(LOG_ALERT,'Excessive login attempts ('.$_POST['username'].')', $alert,($cfg->alertONLoginError()));
     
-        }elseif($_SESSION['_staff']['strikes']%2==0){ //Log every other failed login attempt as a warning.
+        } elseif($_SESSION['_staff']['strikes']%2==0) { //Log every other failed login attempt as a warning.
             $alert='Username: '.$_POST['username']."\n".'IP: '.$_SERVER['REMOTE_ADDR'].
                    "\n".'TIME: '.date('M j, Y, g:i a T')."\n\n".'Attempts #'.$_SESSION['_staff']['strikes'];
-            Sys::log(LOG_WARNING,'Failed staff login attempt ('.$_POST['username'].')',$alert);
+            Sys::log(LOG_WARNING,'Failed staff login attempt ('.$_POST['username'].')', $alert);
         }
 
         return false;
     }
 
-    function create($vars,&$errors) {
-        if(($id=self::save(0,$vars,$errors)) && $vars['teams'] && ($self=Staff::lookup($id)))
+    function create($vars, &$errors) {
+        if(($id=self::save(0, $vars, $errors)) && $vars['teams'] && ($self=Staff::lookup($id)))
             $staff->updateTeams($vars['teams']);
 
         return $id;
     }
 
-    function save($id,$vars,&$errors) {
+    function save($id, $vars, &$errors) {
             
         $vars['username']=Format::striptags($vars['username']);
         $vars['firstname']=Format::striptags($vars['firstname']);
@@ -586,13 +591,13 @@ class Staff {
         if($vars['mobile'] && !Validator::is_phone($vars['mobile']))
             $errors['mobile']='Valid number required';
 
-        if($vars['passwd1'] || $vars['passwd2'] || !$id){
-            if(!$vars['passwd1'] && !$id){
+        if($vars['passwd1'] || $vars['passwd2'] || !$id) {
+            if(!$vars['passwd1'] && !$id) {
                 $errors['passwd1']='Temp. password required';
                 $errors['temppasswd']='Required';
-            }elseif($vars['passwd1'] && strlen($vars['passwd1'])<6){
+            } elseif($vars['passwd1'] && strlen($vars['passwd1'])<6) {
                 $errors['passwd1']='Must be at least 6 characters';
-            }elseif($vars['passwd1'] && strcmp($vars['passwd1'],$vars['passwd2'])){
+            } elseif($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2'])) {
                 $errors['passwd2']='Password(s) do not match';
             }
         }
@@ -609,30 +614,30 @@ class Staff {
         if($errors) return false;
 
             
-        $sql=' SET updated=NOW() '.
-             ',isadmin='.db_input($vars['isadmin']).
-             ',isactive='.db_input($vars['isactive']).
-             ',isvisible='.db_input(isset($vars['isvisible'])?1:0).
-             ',onvacation='.db_input(isset($vars['onvacation'])?1:0).
-             ',assigned_only='.db_input(isset($vars['assigned_only'])?1:0).
-             ',dept_id='.db_input($vars['dept_id']).
-             ',group_id='.db_input($vars['group_id']).
-             ',timezone_id='.db_input($vars['timezone_id']).
-             ',username='.db_input($vars['username']).
-             ',firstname='.db_input($vars['firstname']).
-             ',lastname='.db_input($vars['lastname']).
-             ',email='.db_input($vars['email']).
-             ',phone="'.db_input(Format::phone($vars['phone']),false).'"'.
-             ',phone_ext='.db_input($vars['phone_ext']).
-             ',mobile="'.db_input(Format::phone($vars['mobile']),false).'"'.
-             ',signature='.db_input($vars['signature']).
-             ',notes='.db_input($vars['notes']);
+        $sql='SET updated=NOW() '
+            .' ,isadmin='.db_input($vars['isadmin'])
+            .' ,isactive='.db_input($vars['isactive'])
+            .' ,isvisible='.db_input(isset($vars['isvisible'])?1:0)
+            .' ,onvacation='.db_input(isset($vars['onvacation'])?1:0)
+            .' ,assigned_only='.db_input(isset($vars['assigned_only'])?1:0)
+            .' ,dept_id='.db_input($vars['dept_id'])
+            .' ,group_id='.db_input($vars['group_id'])
+            .' ,timezone_id='.db_input($vars['timezone_id'])
+            .' ,username='.db_input($vars['username'])
+            .' ,firstname='.db_input($vars['firstname'])
+            .' ,lastname='.db_input($vars['lastname'])
+            .' ,email='.db_input($vars['email'])
+            .' ,phone="'.db_input(Format::phone($vars['phone']),false).'"'
+            .' ,phone_ext='.db_input($vars['phone_ext'])
+            .' ,mobile="'.db_input(Format::phone($vars['mobile']),false).'"'
+            .' ,signature='.db_input($vars['signature'])
+            .' ,notes='.db_input($vars['notes']);
             
         if($vars['passwd1'])
-            $sql.=',passwd='.db_input(Passwd::hash($vars['passwd1']));
+            $sql.=' ,passwd='.db_input(Passwd::hash($vars['passwd1']));
                 
         if(isset($vars['change_passwd']))
-            $sql.=',change_passwd=1';
+            $sql.=' ,change_passwd=1';
             
         if($id) {
             $sql='UPDATE '.STAFF_TABLE.' '.$sql.' WHERE staff_id='.db_input($id);
@@ -640,8 +645,8 @@ class Staff {
                 return true;
                 
             $errors['err']='Unable to update the user. Internal error occurred';
-        }else{
-            $sql='INSERT INTO '.STAFF_TABLE.' '.$sql.',created=NOW()';
+        } else {
+            $sql='INSERT INTO '.STAFF_TABLE.' '.$sql.', created=NOW()';
             if(db_query($sql) && ($uid=db_insert_id()))
                 return $uid;
                 
@@ -650,7 +655,5 @@ class Staff {
 
         return false;
     }
-
-
 }
 ?>
diff --git a/include/class.ticket.php b/include/class.ticket.php
index e887daae7d58ea040d13d72ed342f453fc801290..0ad4ab2f366b1dd05e3ba322f177f1656ec85560 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;
@@ -171,7 +174,7 @@ class Ticket{
         if(!is_object($staff) && !($staff=Staff::lookup($staff)))
             return false;
 
-        return ($staff->canAccessDept($this->getDeptId())
+        return ((!$staff->showAssignedOnly() && $staff->canAccessDept($this->getDeptId()))
                  || ($this->getTeamId() && $staff->isTeamMember($this->getTeamId()))
                  || $staff->getId()==$this->getStaffId());
     }
@@ -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()));
     }
@@ -971,13 +1019,13 @@ class Ticket{
     function onOverdue($whine=true) {
         global $cfg;
 
-        // TODO: log overdue events here
+        if($whine && ($sla=$this->getSLA()) && !$sla->alertOnOverdue())
+            $whine = false;
 
         //check if we need to send alerts.
         if(!$whine || !$cfg->alertONOverdueTicket())
             return true;
 
-
         //Get template.
         if(!($tpl = $dept->getTemplate()))
             $tpl= $cfg->getDefaultTemplate();
@@ -1072,15 +1120,15 @@ class Ticket{
         if($this->isOverdue())
             return true;
 
-        $sql='UPDATE '.TICKET_TABLE.' SET isoverdue=1,updated=NOW() '
+        $sql='UPDATE '.TICKET_TABLE.' SET isoverdue=1, updated=NOW() '
             .' WHERE ticket_id='.db_input($this->getId());
 
         if(!db_query($sql) || !db_affected_rows())
             return false;
 
         $this->onOverdue($whine);
-
         $this->track('overdue');
+
         return true;
     }
 
@@ -1668,13 +1716,14 @@ class Ticket{
                 ON (assigned.ticket_id=ticket.ticket_id AND assigned.status=\'open\' AND assigned.staff_id='.db_input($staff->getId()).')'
             .' LEFT JOIN '.TICKET_TABLE.' closed
                 ON (closed.ticket_id=ticket.ticket_id AND closed.status=\'closed\' AND closed.staff_id='.db_input($staff->getId()).')'
-            .' WHERE (ticket.dept_id IN('.implode(',',$staff->getDepts()).') OR ticket.staff_id='.db_input($staff->getId());
-    
-        
+            .' WHERE (ticket.staff_id='.db_input($staff->getId());
+
         if(($teams=$staff->getTeams()))
             $sql.=' OR ticket.team_id IN('.implode(',', array_filter($teams)).')';
 
-    
+        if(!$staff->showAssignedOnly()) //Staff with limited access just see Assigned tickets.
+            $sql.=' OR ticket.dept_id IN('.implode(',',$staff->getDepts()).') ';
+
         $sql.=')';
 
 
@@ -1708,16 +1757,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 +1843,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 +1850,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 +1954,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;
     }
 
@@ -2013,23 +2044,24 @@ class Ticket{
     
     }
    
-    function checkOverdue(){
+    function checkOverdue() {
        
-        $sql='SELECT ticket_id FROM '.TICKET_TABLE.' T1 JOIN '.
-             SLA_TABLE.' T2 ON T1.sla_id=T2.id '.
-             'WHERE status=\'open\' AND isoverdue=0 '.
-             ' AND ((reopened is NULL AND duedate is NULL AND TIME_TO_SEC(TIMEDIFF(NOW(),T1.created))>=grace_period*3600)'.
-             ' OR (reopened is NOT NULL AND duedate is NULL AND TIME_TO_SEC(TIMEDIFF(NOW(),reopened))>=grace_period*3600)'.
-             ' OR (duedate is NOT NULL AND duedate<NOW()) '.
-             ') ORDER BY T1.created LIMIT 50'; //Age upto 50 tickets at a time?
+        $sql='SELECT ticket_id FROM '.TICKET_TABLE.' T1 '
+            .' JOIN '.SLA_TABLE.' T2 ON (T1.sla_id=T2.id) '
+            .' WHERE status=\'open\' AND isoverdue=0 '
+            .' AND ((reopened is NULL AND duedate is NULL AND TIME_TO_SEC(TIMEDIFF(NOW(),T1.created))>=T2.grace_period*3600) '
+            .' OR (reopened is NOT NULL AND duedate is NULL AND TIME_TO_SEC(TIMEDIFF(NOW(),reopened))>=T2.grace_period*3600) '
+            .' OR (duedate is NOT NULL AND duedate<NOW()) '
+            .' ) ORDER BY T1.created LIMIT 50'; //Age upto 50 tickets at a time?
         //echo $sql;
-        if(($stale=db_query($sql)) && db_num_rows($stale)){
-            while(list($id)=db_fetch_row($stale)){
+        if(($res=db_query($sql)) && db_num_rows($res)) {
+            while(list($id)=db_fetch_row($res)) {
                 if(($ticket=Ticket::lookup($id)) && $ticket->markOverdue())
-                    $ticket->logActivity('Ticket Marked Overdue','Ticket flagged as overdue by the system.');
-                    # TODO: Send out notifications about the now-overdue
-                    # ticket XXX: markOverdue sends out notifications.
+                    $ticket->logActivity('Ticket Marked Overdue', 'Ticket flagged as overdue by the system.');
             }
+        } else {
+            //TODO: Trigger escalation on already overdue tickets - make sure last overdue event > grace_period.
+
         }
    }
     
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/include/staff/header.inc.php b/include/staff/header.inc.php
index 0fabe6585d42dbcdcc6f5b1e769fb145f01cc356..58d4f28dcdf77cbe3fa184e8a4979982b01de0fe 100644
--- a/include/staff/header.inc.php
+++ b/include/staff/header.inc.php
@@ -1,7 +1,12 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
-    <meta charset="utf-8">
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <?php
+    if(defined('AUTO_REFRESH') && is_numeric(AUTO_REFRESH_RATE) && AUTO_REFRESH_RATE>0){ //Refresh rate
+    echo '<meta http-equiv="refresh" content="'.AUTO_REFRESH_RATE.'" />';
+    }
+    ?>
     <title>osTicket Staff Control Panel</title>
     <!--[if IE]>
     <style type="text/css">
diff --git a/include/staff/tickets.inc.php b/include/staff/tickets.inc.php
index ef3d3a312c350e552ec02f4f6c79476570705703..67d270c3f033e0db98e901d66b09fdcabf5247c6 100644
--- a/include/staff/tickets.inc.php
+++ b/include/staff/tickets.inc.php
@@ -61,9 +61,13 @@ $qwhere ='';
 
 $depts=$thisstaff->getDepts();    
 $qwhere =' WHERE ( '
-        .'  ticket.dept_id IN ('.($depts?implode(',',$depts):0).') OR ticket.staff_id='.$thisstaff->getId();
+        .'  ticket.staff_id='.db_input($thisstaff->getId());
+if(!$thisstaff->showAssignedOnly())
+    $qwhere.=' OR ticket.dept_id IN ('.($depts?implode(',',$depts):0).')';
+
 if(($teams=$thisstaff->getTeams()) && count(array_filter($teams)))
     $qwhere.=' OR ticket.team_id IN('.implode(',',array_filter($teams)).') ';
+
 $qwhere .= ' )';
 
 //STATUS
@@ -85,7 +89,7 @@ if($staffId && ($staffId==$thisstaff->getId())) { //Staff's assigned tickets.
 }
 
 //******* Showing assigned tickets? (don't confuse it with show assigned To column). F'it it's confusing - just trust me! ***/
-if(!($cfg->showAssignedTickets() || $thisstaff->showAssignedTickets()) && strcasecmp($status,'closed'))
+if(!($cfg->showAssignedTickets() || $thisstaff->showAssignedTickets()) && strcasecmp($status,'closed') && !$search)
     $sql.=' AND (ticket.staff_id=0 OR ticket.staff_id='.db_input($thisstaff->getId()).') ';
 
 //Search?? Somebody...get me some coffee 
diff --git a/scp/js/scp.js b/scp/js/scp.js
index 08da6525eef13c66bfbfd9136a9961fdfebadcda..7a9e0e218d1da97b3ec4b2860f307dd1c1769d1f 100644
--- a/scp/js/scp.js
+++ b/scp/js/scp.js
@@ -210,7 +210,6 @@ $(document).ready(function(){
             });
         },
         onselect: function (obj) {
-            $('#basic-ticket-search').val(obj.id); /*overwriting email*/
             $('#basic-ticket-search').closest('form').submit();
         },
         property: "value"
diff --git a/scp/tickets.php b/scp/tickets.php
index 9fb1e9cf7f0612e8f600af2e911ae58e02f2c9f9..c881381e0d9ff9613b1e26e1df6c410157df664b 100644
--- a/scp/tickets.php
+++ b/scp/tickets.php
@@ -435,12 +435,20 @@ if($stats['overdue']) {
         $sysnotice=$stats['overdue'] .' overdue tickets!';
 }
 
-$nav->addSubMenu(array('desc'=>'Closed Tickets',
-                       'title'=>'Closed Tickets',
-                       'href'=>'tickets.php?status=closed',
-                       'iconclass'=>'closedTickets'),
-                    ($_REQUEST['status']=='closed'));
+if($thisstaff->showAssignedOnly() && $stats['closed']) {
+    $nav->addSubMenu(array('desc'=>'My Closed Tickets ('.$stats['closed'].')',
+                           'title'=>'My Closed Tickets',
+                           'href'=>'tickets.php?status=closed',
+                           'iconclass'=>'closedTickets'),
+                        ($_REQUEST['status']=='closed'));
+} else {
 
+    $nav->addSubMenu(array('desc'=>'Closed Tickets',
+                           'title'=>'Closed Tickets',
+                           'href'=>'tickets.php?status=closed',
+                           'iconclass'=>'closedTickets'),
+                        ($_REQUEST['status']=='closed'));
+}
 
 if($thisstaff->canCreateTickets()) {
     $nav->addSubMenu(array('desc'=>'New Ticket',
@@ -456,7 +464,7 @@ if($ticket) {
     $inc = 'ticket-view.inc.php';
     if($_REQUEST['a']=='edit' && $thisstaff->canEditTickets()) 
         $inc = 'ticket-edit.inc.php';
-}else {
+} else {
     $inc = 'tickets.inc.php';
     if($_REQUEST['a']=='open' && $thisstaff->canCreateTickets())
         $inc = 'ticket-open.inc.php';
@@ -470,8 +478,14 @@ if($ticket) {
         elseif (!Export::saveTickets($query, "tickets-$ts.csv", 'csv'))
             $errors['err'] = 'Internal error: Unable to dump query results';
     }
-    elseif(!$_POST && $_REQUEST['a']!='search'  && ($min=$thisstaff->getRefreshRate()))
-        define('AUTO_REFRESH',1); //set refresh rate if the user has it configured
+
+    //Clear active submenu on search with no status
+    if($_REQUEST['a']=='search' && !$_REQUEST['status'])
+        $nav->setActiveSubMenu(-1);
+
+    //set refresh rate if the user has it configured
+    if(!$_POST && $_REQUEST['a']!='search'  && ($min=$thisstaff->getRefreshRate()))
+        define('AUTO_REFRESH', $min*60); 
 }
 
 require_once(STAFFINC_DIR.'header.inc.php');
diff --git a/setup/inc/sql/osticket-v1.7-mysql.sql b/setup/inc/sql/osticket-v1.7-mysql.sql
index a9966d536dd99e68378bc163e02da729b066352c..e6401d89f668d4c933b7dc0ab6e94b3642657bcd 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` (
@@ -446,8 +447,8 @@ CREATE TABLE `%TABLE_PREFIX%sla` (
 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
 
 INSERT INTO `%TABLE_PREFIX%sla` (`isactive`, `enable_priority_escalation`,
-        `disable_overdue_alerts`, `grace_period`, `name`, `notes`)
-    VALUES (1, 1, 0, 48, 'Default SLA', NULL);
+        `disable_overdue_alerts`, `grace_period`, `name`, `notes`, `created`, `updated`)
+    VALUES (1, 1, 0, 48, 'Default SLA', NULL, NOW(), NOW());
 
 DROP TABLE IF EXISTS `%TABLE_PREFIX%staff`;
 CREATE TABLE `%TABLE_PREFIX%staff` (
diff --git a/setup/inc/sql/v1.6st-1.7-upgrade-mysql.sql b/setup/inc/sql/v1.6st-1.7-upgrade-mysql.sql
index eb7442a5f9f4a13191f7d0cd1c97f8c5c8ec3d4b..efeb8de6f26eb4e4c4a5e10140147c5b1ebdd3c6 100644
--- a/setup/inc/sql/v1.6st-1.7-upgrade-mysql.sql
+++ b/setup/inc/sql/v1.6st-1.7-upgrade-mysql.sql
@@ -78,8 +78,8 @@ CREATE TABLE IF NOT EXISTS `%TICKET_PREFIX%sla` (
  
 -- Create a default SLA
 INSERT INTO `%TABLE_PREFIX%sla` (`isactive`, `enable_priority_escalation`,
-        `disable_overdue_alerts`, `grace_period`, `name`, `notes`)
-    VALUES (1, 1, 0, 48, 'Default SLA', NULL);
+        `disable_overdue_alerts`, `grace_period`, `name`, `notes`, `created`, `updated`)
+    VALUES (1, 1, 0, 48, 'Default SLA', NULL, NOW(), NOW());
 
 -- Create a TEAM table
 CREATE TABLE IF NOT EXISTS `%TABLE_PREFIX%team` (