diff --git a/api/api.inc.php b/api/api.inc.php
index d209860d5c60bff7d55c3032144ea675b4de6767..926a0e2a9ddb4b0464c5f1385e56665312339d8e 100644
--- a/api/api.inc.php
+++ b/api/api.inc.php
@@ -36,13 +36,13 @@ define('OSTAPIINC',TRUE); // Define tag that included files can check
 $remotehost=(isset($_SERVER['HTTP_HOST']) || isset($_SERVER['REMOTE_ADDR']))?TRUE:FALSE;
 /* API exit helper */
 function api_exit($code,$msg='') {
-    global $remotehost,$cfg;
+    global $remotehost, $ost;
     
     if($code!=EX_SUCCESS) {
         //Error occured...
         $_SESSION['api']['errors']+=1;
         $_SESSION['api']['time']=time();
-        Sys::log(LOG_WARNING,"API error - code #$code",$msg);
+        $ost->logWarning("API error - code #$code",$msg);
         //echo "API Error:.$msg";
     }
     if($remotehost){
diff --git a/api/cron.php b/api/cron.php
index 86de02cdb6e32a4f3f61e5fc87a2567133694f82..a8874e3b7eb45eb246145e756db8f85c91c1e47a 100644
--- a/api/cron.php
+++ b/api/cron.php
@@ -17,5 +17,5 @@
 require('api.inc.php');
 require_once(INCLUDE_DIR.'class.cron.php');
 Cron::run();
-Sys::log(LOG_DEBUG,'Cron Job','External cron job executed ['.$_SERVER['REMOTE_ADDR'].']');
+$ost->logDebug('Cron Job','External cron job executed ['.$_SERVER['REMOTE_ADDR'].']');
 ?>
diff --git a/client.inc.php b/client.inc.php
index 3b450e9e2491653ec44c65f346ef79758cc1d1a8..1908eaa1b5d5172fffaccfbee69f6f17e4871d1e 100644
--- a/client.inc.php
+++ b/client.inc.php
@@ -29,7 +29,7 @@ define('OSTCLIENTINC',TRUE);
 define('ASSETS_PATH',ROOT_PATH.'assets/default/');
 
 //Check the status of the HelpDesk.
-if(!is_object($cfg) || !$cfg->getId() || $cfg->isHelpDeskOffline() || $cfg->isUpgradePending()) {
+if(!is_object($ost) || !$ost->isSystemOnline()) {
     include('./offline.php');
     exit;
 }
diff --git a/css/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png b/css/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png
new file mode 100644
index 0000000000000000000000000000000000000000..954e22dbd99e8c6dd7091335599abf2d10bf8003
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png differ
diff --git a/css/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png b/css/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png
new file mode 100644
index 0000000000000000000000000000000000000000..64ece5707d91a6edf9fad4bfcce0c4dbcafcf58d
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png differ
diff --git a/css/ui-lightness/images/ui-bg_flat_10_000000_40x100.png b/css/ui-lightness/images/ui-bg_flat_10_000000_40x100.png
new file mode 100644
index 0000000000000000000000000000000000000000..abdc01082bf3534eafecc5819d28c9574d44ea89
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_flat_10_000000_40x100.png differ
diff --git a/css/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png b/css/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png
new file mode 100644
index 0000000000000000000000000000000000000000..9b383f4d2eab09c0f2a739d6b232c32934bc620b
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png differ
diff --git a/css/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png b/css/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png
new file mode 100644
index 0000000000000000000000000000000000000000..a23baad25b1d1ff36e17361eab24271f2e9b7326
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png differ
diff --git a/css/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png b/css/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png
new file mode 100644
index 0000000000000000000000000000000000000000..42ccba269b6e91bef12ad0fa18be651b5ef0ee68
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png differ
diff --git a/css/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png b/css/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png
new file mode 100644
index 0000000000000000000000000000000000000000..39d5824d6af5456f1e89fc7847ea3599ea5fd815
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png differ
diff --git a/css/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png b/css/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png
new file mode 100644
index 0000000000000000000000000000000000000000..f1273672d253263b7564e9e21d69d7d9d0b337d9
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png differ
diff --git a/css/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png b/css/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png
new file mode 100644
index 0000000000000000000000000000000000000000..359397acffdd84bd102f0e8a951c9d744f278db5
Binary files /dev/null and b/css/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png differ
diff --git a/css/ui-lightness/images/ui-icons_222222_256x240.png b/css/ui-lightness/images/ui-icons_222222_256x240.png
new file mode 100644
index 0000000000000000000000000000000000000000..b273ff111d219c9b9a8b96d57683d0075fb7871a
Binary files /dev/null and b/css/ui-lightness/images/ui-icons_222222_256x240.png differ
diff --git a/css/ui-lightness/images/ui-icons_228ef1_256x240.png b/css/ui-lightness/images/ui-icons_228ef1_256x240.png
new file mode 100644
index 0000000000000000000000000000000000000000..a641a371afa0fbb08ba599dc7ddf14b9bfc3c84f
Binary files /dev/null and b/css/ui-lightness/images/ui-icons_228ef1_256x240.png differ
diff --git a/css/ui-lightness/images/ui-icons_ef8c08_256x240.png b/css/ui-lightness/images/ui-icons_ef8c08_256x240.png
new file mode 100644
index 0000000000000000000000000000000000000000..85e63e9f604ce042d59eb06a8428eeb7cb7896c9
Binary files /dev/null and b/css/ui-lightness/images/ui-icons_ef8c08_256x240.png differ
diff --git a/css/ui-lightness/images/ui-icons_ffd27a_256x240.png b/css/ui-lightness/images/ui-icons_ffd27a_256x240.png
new file mode 100644
index 0000000000000000000000000000000000000000..e117effa3dca24e7978cfc5f8b967f661e81044f
Binary files /dev/null and b/css/ui-lightness/images/ui-icons_ffd27a_256x240.png differ
diff --git a/css/ui-lightness/images/ui-icons_ffffff_256x240.png b/css/ui-lightness/images/ui-icons_ffffff_256x240.png
new file mode 100644
index 0000000000000000000000000000000000000000..42f8f992c727ddaa617da224a522e463df690387
Binary files /dev/null and b/css/ui-lightness/images/ui-icons_ffffff_256x240.png differ
diff --git a/css/ui-lightness/jquery-ui-1.8.18.custom.css b/css/ui-lightness/jquery-ui-1.8.18.custom.css
new file mode 100755
index 0000000000000000000000000000000000000000..d9e8e3a5a914d18948c9ebddfcb3b8d50929bd3a
--- /dev/null
+++ b/css/ui-lightness/jquery-ui-1.8.18.custom.css
@@ -0,0 +1,354 @@
+/*
+ * jQuery UI CSS Framework 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Theming/API
+ */
+
+/* Layout helpers
+----------------------------------*/
+.ui-helper-hidden { display: none; }
+.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
+.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
+.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; }
+.ui-helper-clearfix:after { clear: both; }
+.ui-helper-clearfix { zoom: 1; }
+.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
+
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-disabled { cursor: default !important; }
+
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Overlays */
+.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+
+
+/*
+ * jQuery UI CSS Framework 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Theming/API
+ *
+ * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS,%20Tahoma,%20Verdana,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=12_gloss_wave.png&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=03_highlight_soft.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=08_diagonals_thick.png&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=01_flat.png&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px
+ */
+
+
+/* Component containers
+----------------------------------*/
+.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1.1em; }
+.ui-widget .ui-widget { font-size: 1em; }
+.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1em; }
+.ui-widget-content { border: 1px solid #dddddd; background: #eeeeee url(images/ui-bg_highlight-soft_100_eeeeee_1x100.png) 50% top repeat-x; color: #333333; }
+.ui-widget-content a { color: #333333; }
+.ui-widget-header { border: 1px solid #e78f08; background: #f6a828 url(images/ui-bg_gloss-wave_35_f6a828_500x100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; }
+.ui-widget-header a { color: #ffffff; }
+
+/* Interaction states
+----------------------------------*/
+.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6 url(images/ui-bg_glass_100_f6f6f6_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #1c94c4; }
+.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #1c94c4; text-decoration: none; }
+.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce url(images/ui-bg_glass_100_fdf5ce_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #c77405; }
+.ui-state-hover a, .ui-state-hover a:hover { color: #c77405; text-decoration: none; }
+.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #fbd850; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #eb8f00; }
+.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; text-decoration: none; }
+.ui-widget :active { outline: none; }
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight  {border: 1px solid #fed22f; background: #ffe45c url(images/ui-bg_highlight-soft_75_ffe45c_1x100.png) 50% top repeat-x; color: #363636; }
+.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
+.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #b81900 url(images/ui-bg_diagonals-thick_18_b81900_40x40.png) 50% 50% repeat; color: #ffffff; }
+.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; }
+.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; }
+.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
+.ui-priority-secondary, .ui-widget-content .ui-priority-secondary,  .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
+.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-widget-header .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); }
+.ui-state-default .ui-icon { background-image: url(images/ui-icons_ef8c08_256x240.png); }
+.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_ef8c08_256x240.png); }
+.ui-state-active .ui-icon {background-image: url(images/ui-icons_ef8c08_256x240.png); }
+.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_228ef1_256x240.png); }
+.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_ffd27a_256x240.png); }
+
+/* positioning */
+.ui-icon-carat-1-n { background-position: 0 0; }
+.ui-icon-carat-1-ne { background-position: -16px 0; }
+.ui-icon-carat-1-e { background-position: -32px 0; }
+.ui-icon-carat-1-se { background-position: -48px 0; }
+.ui-icon-carat-1-s { background-position: -64px 0; }
+.ui-icon-carat-1-sw { background-position: -80px 0; }
+.ui-icon-carat-1-w { background-position: -96px 0; }
+.ui-icon-carat-1-nw { background-position: -112px 0; }
+.ui-icon-carat-2-n-s { background-position: -128px 0; }
+.ui-icon-carat-2-e-w { background-position: -144px 0; }
+.ui-icon-triangle-1-n { background-position: 0 -16px; }
+.ui-icon-triangle-1-ne { background-position: -16px -16px; }
+.ui-icon-triangle-1-e { background-position: -32px -16px; }
+.ui-icon-triangle-1-se { background-position: -48px -16px; }
+.ui-icon-triangle-1-s { background-position: -64px -16px; }
+.ui-icon-triangle-1-sw { background-position: -80px -16px; }
+.ui-icon-triangle-1-w { background-position: -96px -16px; }
+.ui-icon-triangle-1-nw { background-position: -112px -16px; }
+.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
+.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
+.ui-icon-arrow-1-n { background-position: 0 -32px; }
+.ui-icon-arrow-1-ne { background-position: -16px -32px; }
+.ui-icon-arrow-1-e { background-position: -32px -32px; }
+.ui-icon-arrow-1-se { background-position: -48px -32px; }
+.ui-icon-arrow-1-s { background-position: -64px -32px; }
+.ui-icon-arrow-1-sw { background-position: -80px -32px; }
+.ui-icon-arrow-1-w { background-position: -96px -32px; }
+.ui-icon-arrow-1-nw { background-position: -112px -32px; }
+.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
+.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
+.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
+.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
+.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
+.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
+.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
+.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
+.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
+.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
+.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
+.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
+.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
+.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
+.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
+.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
+.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
+.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
+.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
+.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
+.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
+.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
+.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
+.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
+.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
+.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
+.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
+.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
+.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
+.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
+.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
+.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
+.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
+.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
+.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
+.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
+.ui-icon-arrow-4 { background-position: 0 -80px; }
+.ui-icon-arrow-4-diag { background-position: -16px -80px; }
+.ui-icon-extlink { background-position: -32px -80px; }
+.ui-icon-newwin { background-position: -48px -80px; }
+.ui-icon-refresh { background-position: -64px -80px; }
+.ui-icon-shuffle { background-position: -80px -80px; }
+.ui-icon-transfer-e-w { background-position: -96px -80px; }
+.ui-icon-transferthick-e-w { background-position: -112px -80px; }
+.ui-icon-folder-collapsed { background-position: 0 -96px; }
+.ui-icon-folder-open { background-position: -16px -96px; }
+.ui-icon-document { background-position: -32px -96px; }
+.ui-icon-document-b { background-position: -48px -96px; }
+.ui-icon-note { background-position: -64px -96px; }
+.ui-icon-mail-closed { background-position: -80px -96px; }
+.ui-icon-mail-open { background-position: -96px -96px; }
+.ui-icon-suitcase { background-position: -112px -96px; }
+.ui-icon-comment { background-position: -128px -96px; }
+.ui-icon-person { background-position: -144px -96px; }
+.ui-icon-print { background-position: -160px -96px; }
+.ui-icon-trash { background-position: -176px -96px; }
+.ui-icon-locked { background-position: -192px -96px; }
+.ui-icon-unlocked { background-position: -208px -96px; }
+.ui-icon-bookmark { background-position: -224px -96px; }
+.ui-icon-tag { background-position: -240px -96px; }
+.ui-icon-home { background-position: 0 -112px; }
+.ui-icon-flag { background-position: -16px -112px; }
+.ui-icon-calendar { background-position: -32px -112px; }
+.ui-icon-cart { background-position: -48px -112px; }
+.ui-icon-pencil { background-position: -64px -112px; }
+.ui-icon-clock { background-position: -80px -112px; }
+.ui-icon-disk { background-position: -96px -112px; }
+.ui-icon-calculator { background-position: -112px -112px; }
+.ui-icon-zoomin { background-position: -128px -112px; }
+.ui-icon-zoomout { background-position: -144px -112px; }
+.ui-icon-search { background-position: -160px -112px; }
+.ui-icon-wrench { background-position: -176px -112px; }
+.ui-icon-gear { background-position: -192px -112px; }
+.ui-icon-heart { background-position: -208px -112px; }
+.ui-icon-star { background-position: -224px -112px; }
+.ui-icon-link { background-position: -240px -112px; }
+.ui-icon-cancel { background-position: 0 -128px; }
+.ui-icon-plus { background-position: -16px -128px; }
+.ui-icon-plusthick { background-position: -32px -128px; }
+.ui-icon-minus { background-position: -48px -128px; }
+.ui-icon-minusthick { background-position: -64px -128px; }
+.ui-icon-close { background-position: -80px -128px; }
+.ui-icon-closethick { background-position: -96px -128px; }
+.ui-icon-key { background-position: -112px -128px; }
+.ui-icon-lightbulb { background-position: -128px -128px; }
+.ui-icon-scissors { background-position: -144px -128px; }
+.ui-icon-clipboard { background-position: -160px -128px; }
+.ui-icon-copy { background-position: -176px -128px; }
+.ui-icon-contact { background-position: -192px -128px; }
+.ui-icon-image { background-position: -208px -128px; }
+.ui-icon-video { background-position: -224px -128px; }
+.ui-icon-script { background-position: -240px -128px; }
+.ui-icon-alert { background-position: 0 -144px; }
+.ui-icon-info { background-position: -16px -144px; }
+.ui-icon-notice { background-position: -32px -144px; }
+.ui-icon-help { background-position: -48px -144px; }
+.ui-icon-check { background-position: -64px -144px; }
+.ui-icon-bullet { background-position: -80px -144px; }
+.ui-icon-radio-off { background-position: -96px -144px; }
+.ui-icon-radio-on { background-position: -112px -144px; }
+.ui-icon-pin-w { background-position: -128px -144px; }
+.ui-icon-pin-s { background-position: -144px -144px; }
+.ui-icon-play { background-position: 0 -160px; }
+.ui-icon-pause { background-position: -16px -160px; }
+.ui-icon-seek-next { background-position: -32px -160px; }
+.ui-icon-seek-prev { background-position: -48px -160px; }
+.ui-icon-seek-end { background-position: -64px -160px; }
+.ui-icon-seek-start { background-position: -80px -160px; }
+/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
+.ui-icon-seek-first { background-position: -80px -160px; }
+.ui-icon-stop { background-position: -96px -160px; }
+.ui-icon-eject { background-position: -112px -160px; }
+.ui-icon-volume-off { background-position: -128px -160px; }
+.ui-icon-volume-on { background-position: -144px -160px; }
+.ui-icon-power { background-position: 0 -176px; }
+.ui-icon-signal-diag { background-position: -16px -176px; }
+.ui-icon-signal { background-position: -32px -176px; }
+.ui-icon-battery-0 { background-position: -48px -176px; }
+.ui-icon-battery-1 { background-position: -64px -176px; }
+.ui-icon-battery-2 { background-position: -80px -176px; }
+.ui-icon-battery-3 { background-position: -96px -176px; }
+.ui-icon-circle-plus { background-position: 0 -192px; }
+.ui-icon-circle-minus { background-position: -16px -192px; }
+.ui-icon-circle-close { background-position: -32px -192px; }
+.ui-icon-circle-triangle-e { background-position: -48px -192px; }
+.ui-icon-circle-triangle-s { background-position: -64px -192px; }
+.ui-icon-circle-triangle-w { background-position: -80px -192px; }
+.ui-icon-circle-triangle-n { background-position: -96px -192px; }
+.ui-icon-circle-arrow-e { background-position: -112px -192px; }
+.ui-icon-circle-arrow-s { background-position: -128px -192px; }
+.ui-icon-circle-arrow-w { background-position: -144px -192px; }
+.ui-icon-circle-arrow-n { background-position: -160px -192px; }
+.ui-icon-circle-zoomin { background-position: -176px -192px; }
+.ui-icon-circle-zoomout { background-position: -192px -192px; }
+.ui-icon-circle-check { background-position: -208px -192px; }
+.ui-icon-circlesmall-plus { background-position: 0 -208px; }
+.ui-icon-circlesmall-minus { background-position: -16px -208px; }
+.ui-icon-circlesmall-close { background-position: -32px -208px; }
+.ui-icon-squaresmall-plus { background-position: -48px -208px; }
+.ui-icon-squaresmall-minus { background-position: -64px -208px; }
+.ui-icon-squaresmall-close { background-position: -80px -208px; }
+.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
+.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
+.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
+.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
+.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
+.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Corner radius */
+.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; }
+.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; }
+.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
+.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; -khtml-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
+
+/* Overlays */
+.ui-widget-overlay { background: #666666 url(images/ui-bg_diagonals-thick_20_666666_40x40.png) 50% 50% repeat; opacity: .50;filter:Alpha(Opacity=50); }
+.ui-widget-shadow { margin: -5px 0 0 -5px; padding: 5px; background: #000000 url(images/ui-bg_flat_10_000000_40x100.png) 50% 50% repeat-x; opacity: .20;filter:Alpha(Opacity=20); -moz-border-radius: 5px; -khtml-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; }/*
+ * jQuery UI Datepicker 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Datepicker#theming
+ */
+.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
+.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
+.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
+.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
+.ui-datepicker .ui-datepicker-prev { left:2px; }
+.ui-datepicker .ui-datepicker-next { right:2px; }
+.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
+.ui-datepicker .ui-datepicker-next-hover { right:1px; }
+.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px;  }
+.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
+.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
+.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
+.ui-datepicker select.ui-datepicker-month, 
+.ui-datepicker select.ui-datepicker-year { width: 49%;}
+.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
+.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0;  }
+.ui-datepicker td { border: 0; padding: 1px; }
+.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
+.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
+.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
+.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
+
+/* with multiple calendars */
+.ui-datepicker.ui-datepicker-multi { width:auto; }
+.ui-datepicker-multi .ui-datepicker-group { float:left; }
+.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
+.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
+.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
+.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
+.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
+.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }
+
+/* RTL support */
+.ui-datepicker-rtl { direction: rtl; }
+.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+
+/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
+.ui-datepicker-cover {
+    display: none; /*sorry for IE5*/
+    display/**/: block; /*sorry for IE5*/
+    position: absolute; /*must have*/
+    z-index: -1; /*must have*/
+    filter: mask(); /*must have*/
+    top: -4px; /*must have*/
+    left: -4px; /*must have*/
+    width: 200px; /*must have*/
+    height: 200px; /*must have*/
+}
diff --git a/include/class.config.php b/include/class.config.php
index 626e11c9a0e3eb466046f3539b9ed16ecb7c0c7e..cb7cd40aed575013ee1db136d15037438d6b34fb 100644
--- a/include/class.config.php
+++ b/include/class.config.php
@@ -44,39 +44,28 @@ class Config {
             
         $this->config=db_fetch_array($res);
         $this->id=$this->config['id'];
+        $this->setMysqlTZ(db_timezone());
 
         return true;
     }
 
-    //Initialize some default values.
-    function init() {
-        list($mysqltz)=db_fetch_row(db_query('SELECT @@session.time_zone '));
-        $this->setMysqlTZ($mysqltz);
-    }
-    
     function reload() {
         if(!$this->load($this->getId()))
             return false;
 
-        $this->init();
-
         return true;
     }
 
     function isHelpDeskOffline() {
-        return !$this->isSystemOnline();
+        return !$this->isOnline();
     }
 
     function isHelpDeskOnline() {
-        return $this->isSystemOnline();
+        return $this->isOnline();
     }
 
-    function isSystemOnline() {
-        return ($this->config['isonline'] && !$this->isUpgradePending());
-    }
-
-    function isUpgradePending() {
-        return (defined('SCHEMA_SIGNATURE') && strcasecmp($this->getSchemaSignature(), SCHEMA_SIGNATURE));
+    function isOnline() {
+        return ($this->config['isonline']);
     }
 
     function isKnowledgebaseEnabled() {
@@ -132,6 +121,14 @@ class Config {
     function getId() {
         return $this->id;
     }
+
+    function getConfigId() {
+        return $this->getId();
+    }
+
+    function getConfigInfo() {
+        return $this->config;
+    }
    
     function getTitle() {
         return $this->config['helpdesk_title'];
@@ -145,10 +142,6 @@ class Config {
         return rtrim($this->getUrl(),'/');
     }
 
-    function getConfig() {
-        return $this->config;
-    }
-
     function getTZOffset() {
         return $this->config['timezone_offset'];
     }
@@ -584,7 +577,7 @@ class Config {
         return false;
     }
 
-    function updateGeneralSetting($vars,&$errors) {
+    function updateGeneralSetting($vars, &$errors) {
 
         $f=array();
         $f['helpdesk_url']=array('type'=>'string',   'required'=>1, 'error'=>'Helpdesk URl required');
@@ -594,29 +587,29 @@ class Config {
         $f['staff_session_timeout']=array('type'=>'int',   'required'=>1, 'error'=>'Enter idle time in minutes');
         $f['client_session_timeout']=array('type'=>'int',   'required'=>1, 'error'=>'Enter idle time in minutes');
 
-        if(!Validator::process($f,$vars,$errors) || $errors)
+        if(!Validator::process($f, $vars, $errors) || $errors)
             return false;
 
-        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-             ',isonline='.db_input($vars['isonline']).
-             ',helpdesk_title='.db_input($vars['helpdesk_title']).
-             ',helpdesk_url='.db_input($vars['helpdesk_url']).
-             ',default_dept_id='.db_input($vars['default_dept_id']).
-             ',default_template_id='.db_input($vars['default_template_id']).
-             ',max_page_size='.db_input($vars['max_page_size']).
-             ',log_level='.db_input($vars['log_level']).
-             ',log_graceperiod='.db_input($vars['log_graceperiod']).
-             ',passwd_reset_period='.db_input($vars['passwd_reset_period']).
-             ',staff_max_logins='.db_input($vars['staff_max_logins']).
-             ',staff_login_timeout='.db_input($vars['staff_login_timeout']).
-             ',staff_session_timeout='.db_input($vars['staff_session_timeout']).
-             ',staff_ip_binding='.db_input(isset($vars['staff_ip_binding'])?1:0).
-             ',client_max_logins='.db_input($vars['client_max_logins']).
-             ',client_login_timeout='.db_input($vars['client_login_timeout']).
-             ',client_session_timeout='.db_input($vars['client_session_timeout']).
-             ',clickable_urls='.db_input(isset($vars['clickable_urls'])?1:0).
-             ',enable_auto_cron='.db_input(isset($vars['enable_auto_cron'])?1:0).
-             ' WHERE id='.$this->getId();
+        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+            .',isonline='.db_input($vars['isonline'])
+            .',helpdesk_title='.db_input($vars['helpdesk_title'])
+            .',helpdesk_url='.db_input($vars['helpdesk_url'])
+            .',default_dept_id='.db_input($vars['default_dept_id'])
+            .',default_template_id='.db_input($vars['default_template_id'])
+            .',max_page_size='.db_input($vars['max_page_size'])
+            .',log_level='.db_input($vars['log_level'])
+            .',log_graceperiod='.db_input($vars['log_graceperiod'])
+            .',passwd_reset_period='.db_input($vars['passwd_reset_period'])
+            .',staff_max_logins='.db_input($vars['staff_max_logins'])
+            .',staff_login_timeout='.db_input($vars['staff_login_timeout'])
+            .',staff_session_timeout='.db_input($vars['staff_session_timeout'])
+            .',staff_ip_binding='.db_input(isset($vars['staff_ip_binding'])?1:0)
+            .',client_max_logins='.db_input($vars['client_max_logins'])
+            .',client_login_timeout='.db_input($vars['client_login_timeout'])
+            .',client_session_timeout='.db_input($vars['client_session_timeout'])
+            .',clickable_urls='.db_input(isset($vars['clickable_urls'])?1:0)
+            .',enable_auto_cron='.db_input(isset($vars['enable_auto_cron'])?1:0)
+            .' WHERE id='.db_input($this->getId());
         
         return (db_query($sql));
     }
@@ -633,14 +626,14 @@ class Config {
         if(!Validator::process($f,$vars,$errors) || $errors)
             return false;
 
-        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-             ',time_format='.db_input($vars['time_format']).
-             ',date_format='.db_input($vars['date_format']).
-             ',datetime_format='.db_input($vars['datetime_format']).
-             ',daydatetime_format='.db_input($vars['daydatetime_format']).
-             ',default_timezone_id='.db_input($vars['default_timezone_id']).
-             ',enable_daylight_saving='.db_input(isset($vars['enable_daylight_saving'])?1:0).
-             ' WHERE id='.$this->getId();
+        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+            .',time_format='.db_input($vars['time_format'])
+            .',date_format='.db_input($vars['date_format'])
+            .',datetime_format='.db_input($vars['datetime_format'])
+            .',daydatetime_format='.db_input($vars['daydatetime_format'])
+            .',default_timezone_id='.db_input($vars['default_timezone_id'])
+            .',enable_daylight_saving='.db_input(isset($vars['enable_daylight_saving'])?1:0)
+            .' WHERE id='.db_input($this->getId());
 
         return (db_query($sql));
     }
@@ -665,22 +658,23 @@ class Config {
         if(!Validator::process($f,$vars,$errors) || $errors)
             return false;
 
-        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-             ',random_ticket_ids='.db_input($vars['random_ticket_ids']).
-             ',default_priority_id='.db_input($vars['default_priority_id']).
-             ',default_sla_id='.db_input($vars['default_sla_id']).
-             ',max_open_tickets='.db_input($vars['max_open_tickets']).
-             ',autolock_minutes='.db_input($vars['autolock_minutes']).
-             ',allow_priority_change='.db_input(isset($vars['allow_priority_change'])?1:0).
-             ',use_email_priority='.db_input(isset($vars['use_email_priority'])?1:0).
-             ',enable_captcha='.db_input(isset($vars['enable_captcha'])?1:0).
-             ',log_ticket_activity='.db_input(isset($vars['log_ticket_activity'])?1:0).
-             ',auto_assign_reopened_tickets='.db_input(isset($vars['auto_assign_reopened_tickets'])?1:0).
-             ',show_assigned_tickets='.db_input(isset($vars['show_assigned_tickets'])?1:0).
-             ',show_answered_tickets='.db_input(isset($vars['show_answered_tickets'])?1:0).
-             ',show_related_tickets='.db_input(isset($vars['show_related_tickets'])?1:0).
-             ',show_notes_inline='.db_input(isset($vars['show_notes_inline'])?1:0).
-             ',hide_staff_name='.db_input(isset($vars['hide_staff_name'])?1:0);
+        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+            .',random_ticket_ids='.db_input($vars['random_ticket_ids'])
+            .',default_priority_id='.db_input($vars['default_priority_id'])
+            .',default_sla_id='.db_input($vars['default_sla_id'])
+            .',max_open_tickets='.db_input($vars['max_open_tickets'])
+            .',autolock_minutes='.db_input($vars['autolock_minutes'])
+            .',allow_priority_change='.db_input(isset($vars['allow_priority_change'])?1:0)
+            .',use_email_priority='.db_input(isset($vars['use_email_priority'])?1:0)
+            .',enable_captcha='.db_input(isset($vars['enable_captcha'])?1:0)
+            .',log_ticket_activity='.db_input(isset($vars['log_ticket_activity'])?1:0)
+            .',auto_assign_reopened_tickets='.db_input(isset($vars['auto_assign_reopened_tickets'])?1:0)
+            .',show_assigned_tickets='.db_input(isset($vars['show_assigned_tickets'])?1:0)
+            .',show_answered_tickets='.db_input(isset($vars['show_answered_tickets'])?1:0)
+            .',show_related_tickets='.db_input(isset($vars['show_related_tickets'])?1:0)
+            .',show_notes_inline='.db_input(isset($vars['show_notes_inline'])?1:0)
+            .',hide_staff_name='.db_input(isset($vars['hide_staff_name'])?1:0)
+            .' WHERE id='.db_input($this->getId());
 
         return (db_query($sql));
     }
@@ -702,15 +696,18 @@ class Config {
         if(!Validator::process($f,$vars,$errors) || $errors)
             return false;
 
-        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-             ',default_email_id='.db_input($vars['default_email_id']).
-             ',alert_email_id='.db_input($vars['alert_email_id']).
-             ',default_smtp_id='.db_input($vars['default_smtp_id']).
-             ',admin_email='.db_input($vars['admin_email']).
-             ',enable_mail_polling='.db_input(isset($vars['enable_mail_polling'])?1:0).
-             ',enable_email_piping='.db_input(isset($vars['enable_email_piping'])?1:0).
-             ',strip_quoted_reply='.db_input(isset($vars['strip_quoted_reply'])?1:0).
-             ',reply_separator='.db_input($vars['reply_separator']);
+        $sql='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+            .',default_email_id='.db_input($vars['default_email_id'])
+            .',alert_email_id='.db_input($vars['alert_email_id'])
+            .',default_smtp_id='.db_input($vars['default_smtp_id'])
+            .',admin_email='.db_input($vars['admin_email'])
+            .',enable_mail_polling='.db_input(isset($vars['enable_mail_polling'])?1:0)
+            .',enable_email_piping='.db_input(isset($vars['enable_email_piping'])?1:0)
+            .',strip_quoted_reply='.db_input(isset($vars['strip_quoted_reply'])?1:0)
+            .',reply_separator='.db_input($vars['reply_separator'])
+            .' WHERE id='.db_input($this->getId());
+
+
         
         return (db_query($sql));
     }
@@ -741,36 +738,33 @@ class Config {
 
         if($errors) return false;
 
-        $sql= 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-              ',allow_attachments='.db_input(isset($vars['allow_attachments'])?1:0).
-              ',allowed_filetypes='.db_input(strtolower(preg_replace("/\n\r|\r\n|\n|\r/", '',trim($vars['allowed_filetypes'])))).
-              ',max_file_size='.db_input($vars['max_file_size']).
-              ',max_user_file_uploads='.db_input($vars['max_user_file_uploads']).
-              ',max_staff_file_uploads='.db_input($vars['max_staff_file_uploads']).
-              ',email_attachments='.db_input(isset($vars['email_attachments'])?1:0).
-              ',allow_email_attachments='.db_input(isset($vars['allow_email_attachments'])?1:0).
-              ',allow_online_attachments='.db_input(isset($vars['allow_online_attachments'])?1:0).
-              ',allow_online_attachments_onlogin='.db_input(isset($vars['allow_online_attachments_onlogin'])?1:0).
-              ' WHERE id='.db_input($this->getId());
-        
+        $sql= 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+             .',allow_attachments='.db_input(isset($vars['allow_attachments'])?1:0)
+             .',allowed_filetypes='.db_input(strtolower(preg_replace("/\n\r|\r\n|\n|\r/", '',trim($vars['allowed_filetypes']))))
+             .',max_file_size='.db_input($vars['max_file_size'])
+             .',max_user_file_uploads='.db_input($vars['max_user_file_uploads'])
+             .',max_staff_file_uploads='.db_input($vars['max_staff_file_uploads'])
+             .',email_attachments='.db_input(isset($vars['email_attachments'])?1:0)
+             .',allow_email_attachments='.db_input(isset($vars['allow_email_attachments'])?1:0)
+             .',allow_online_attachments='.db_input(isset($vars['allow_online_attachments'])?1:0)
+             .',allow_online_attachments_onlogin='.db_input(isset($vars['allow_online_attachments_onlogin'])?1:0)
+             .' WHERE id='.db_input($this->getId());
 
         return (db_query($sql));
-
     }
 
-
     function updateAutoresponderSetting($vars,&$errors) {
 
         if($errors) return false;
 
-        $sql= 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-              ',ticket_autoresponder='.db_input($vars['ticket_autoresponder']).
-              ',message_autoresponder='.db_input($vars['message_autoresponder']).
-              ',ticket_notice_active='.db_input($vars['ticket_notice_active']).
-              ',overlimit_notice_active='.db_input($vars['overlimit_notice_active']);
+        $sql ='UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+             .',ticket_autoresponder='.db_input($vars['ticket_autoresponder'])
+             .',message_autoresponder='.db_input($vars['message_autoresponder'])
+             .',ticket_notice_active='.db_input($vars['ticket_notice_active'])
+             .',overlimit_notice_active='.db_input($vars['overlimit_notice_active'])
+             .' WHERE id='.db_input($this->getId());
 
         return (db_query($sql));
-
     }
 
 
@@ -778,10 +772,11 @@ class Config {
 
         if($errors) return false;
 
-        $sql= 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-              ',enable_kb='.db_input(isset($vars['enable_kb'])?1:0).
-              ',enable_premade='.db_input(isset($vars['enable_premade'])?1:0);
-    
+        $sql = 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+              .',enable_kb='.db_input(isset($vars['enable_kb'])?1:0)
+              .',enable_premade='.db_input(isset($vars['enable_premade'])?1:0)
+              .' WHERE id='.db_input($this->getId());
+
         return (db_query($sql));
     }
 
@@ -832,38 +827,44 @@ class Config {
 
         if($errors) return false;
         
-        $sql= 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '.
-              ',ticket_notice_active='.db_input($vars['ticket_notice_active']).
-              ',ticket_alert_active='.db_input($vars['ticket_alert_active']).
-              ',ticket_alert_admin='.db_input(isset($vars['ticket_alert_admin'])?1:0).
-              ',ticket_alert_dept_manager='.db_input(isset($vars['ticket_alert_dept_manager'])?1:0).
-              ',ticket_alert_dept_members='.db_input(isset($vars['ticket_alert_dept_members'])?1:0).
-              ',message_alert_active='.db_input($vars['message_alert_active']).
-              ',message_alert_laststaff='.db_input(isset($vars['message_alert_laststaff'])?1:0).
-              ',message_alert_assigned='.db_input(isset($vars['message_alert_assigned'])?1:0).
-              ',message_alert_dept_manager='.db_input(isset($vars['message_alert_dept_manager'])?1:0).
-              ',note_alert_active='.db_input($vars['note_alert_active']).
-              ',note_alert_laststaff='.db_input(isset($vars['note_alert_laststaff'])?1:0).
-              ',note_alert_assigned='.db_input(isset($vars['note_alert_assigned'])?1:0).
-              ',note_alert_dept_manager='.db_input(isset($vars['note_alert_dept_manager'])?1:0).
-              ',assigned_alert_active='.db_input($vars['assigned_alert_active']).
-              ',assigned_alert_staff='.db_input(isset($vars['assigned_alert_staff'])?1:0).
-              ',assigned_alert_team_lead='.db_input(isset($vars['assigned_alert_team_lead'])?1:0).
-              ',assigned_alert_team_members='.db_input(isset($vars['assigned_alert_team_members'])?1:0).
-              ',transfer_alert_active='.db_input($vars['transfer_alert_active']).
-              ',transfer_alert_assigned='.db_input(isset($vars['transfer_alert_assigned'])?1:0).
-              ',transfer_alert_dept_manager='.db_input(isset($vars['transfer_alert_dept_manager'])?1:0).
-              ',transfer_alert_dept_members='.db_input(isset($var['transfer_alert_dept_members'])?1:0).
-              ',overdue_alert_active='.db_input($vars['overdue_alert_active']).
-              ',overdue_alert_assigned='.db_input(isset($vars['overdue_alert_assigned'])?1:0).
-              ',overdue_alert_dept_manager='.db_input(isset($vars['overdue_alert_dept_manager'])?1:0).
-              ',overdue_alert_dept_members='.db_input(isset($var['overdue_alert_dept_members'])?1:0).
-              ',send_sys_errors='.db_input(isset($vars['send_sys_errors'])?1:0).
-              ',send_sql_errors='.db_input(isset($vars['send_sql_errors'])?1:0).
-              ',send_login_errors='.db_input(isset($vars['send_login_errors'])?1:0);
+        $sql= 'UPDATE '.CONFIG_TABLE.' SET updated=NOW() '
+             .',ticket_notice_active='.db_input($vars['ticket_notice_active'])
+             .',ticket_alert_active='.db_input($vars['ticket_alert_active'])
+             .',ticket_alert_admin='.db_input(isset($vars['ticket_alert_admin'])?1:0)
+             .',ticket_alert_dept_manager='.db_input(isset($vars['ticket_alert_dept_manager'])?1:0)
+             .',ticket_alert_dept_members='.db_input(isset($vars['ticket_alert_dept_members'])?1:0)
+             .',message_alert_active='.db_input($vars['message_alert_active'])
+             .',message_alert_laststaff='.db_input(isset($vars['message_alert_laststaff'])?1:0)
+             .',message_alert_assigned='.db_input(isset($vars['message_alert_assigned'])?1:0)
+             .',message_alert_dept_manager='.db_input(isset($vars['message_alert_dept_manager'])?1:0)
+             .',note_alert_active='.db_input($vars['note_alert_active'])
+             .',note_alert_laststaff='.db_input(isset($vars['note_alert_laststaff'])?1:0)
+             .',note_alert_assigned='.db_input(isset($vars['note_alert_assigned'])?1:0)
+             .',note_alert_dept_manager='.db_input(isset($vars['note_alert_dept_manager'])?1:0)
+             .',assigned_alert_active='.db_input($vars['assigned_alert_active'])
+             .',assigned_alert_staff='.db_input(isset($vars['assigned_alert_staff'])?1:0)
+             .',assigned_alert_team_lead='.db_input(isset($vars['assigned_alert_team_lead'])?1:0)
+             .',assigned_alert_team_members='.db_input(isset($vars['assigned_alert_team_members'])?1:0)
+             .',transfer_alert_active='.db_input($vars['transfer_alert_active'])
+             .',transfer_alert_assigned='.db_input(isset($vars['transfer_alert_assigned'])?1:0)
+             .',transfer_alert_dept_manager='.db_input(isset($vars['transfer_alert_dept_manager'])?1:0)
+             .',transfer_alert_dept_members='.db_input(isset($var['transfer_alert_dept_members'])?1:0)
+             .',overdue_alert_active='.db_input($vars['overdue_alert_active'])
+             .',overdue_alert_assigned='.db_input(isset($vars['overdue_alert_assigned'])?1:0)
+             .',overdue_alert_dept_manager='.db_input(isset($vars['overdue_alert_dept_manager'])?1:0)
+             .',overdue_alert_dept_members='.db_input(isset($var['overdue_alert_dept_members'])?1:0)
+             .',send_sys_errors='.db_input(isset($vars['send_sys_errors'])?1:0)
+             .',send_sql_errors='.db_input(isset($vars['send_sql_errors'])?1:0)
+             .',send_login_errors='.db_input(isset($vars['send_login_errors'])?1:0)
+             .' WHERE id='.db_input($this->getId());
 
         return (db_query($sql));
 
     }
+
+    /** static **/
+    function lookup($id) {
+        return ($id && ($cfg = new Config($id)) && $cfg->getId()==$id)?$cfg:null;
+    }
 }
 ?>
diff --git a/include/class.cron.php b/include/class.cron.php
index ddc4d2973e77ff93f6f83a4a3fefd6b4b9b82814..c8e3a81def985b99eb0f21eaea8751362e1ced05 100644
--- a/include/class.cron.php
+++ b/include/class.cron.php
@@ -31,7 +31,8 @@ class Cron {
     }
 
     function PurgeLogs() {
-        Sys::purgeLogs();
+        global $ost;
+        if($ost) $ost->purgeLogs();
     }
 
     function CleanOrphanedFiles() {
diff --git a/include/class.email.php b/include/class.email.php
index 0b4317f7e6e6dc82866288fc88631ff601b5753f..dba9a45d5d4c569c9a5e7b2c17c4254f12abdcee 100644
--- a/include/class.email.php
+++ b/include/class.email.php
@@ -122,7 +122,7 @@ class Email {
     }
 
     function send($to, $subject, $message, $attachments=null, $options=null) {
-        global $cfg;
+        global $cfg, $ost;
 
         //Get SMTP info IF enabled!
         $smtp=array();
@@ -149,11 +149,12 @@ class Email {
         $headers = array ('From' => $from,
                           'To' => $to,
                           'Subject' => $subject,
-                          'Date'=>date('D,d M Y H:i:s O'),
+                          'Date'=>date('D, d M Y H:i:s O'),
                           'Message-ID' =>'<'.Misc::randCode(6).''.time().'-'.$this->getEmail().'>',
                           'X-Mailer' =>'osTicket v1.7',
                           'Content-Type' => 'text/html; charset="UTF-8"'
                           );
+
         $mime = new Mail_mime();
         $mime->setTXTBody($body);
         //XXX: Attachments
@@ -189,8 +190,9 @@ class Email {
             if(!PEAR::isError($result))
                 return true;
 
+            //SMTP failed - log error.
             $alert=sprintf("Unable to email via %s:%d [%s]\n\n%s\n",$smtp['host'],$smtp['port'],$smtp['username'],$result->getMessage());
-            Sys::log(LOG_ALERT,'SMTP Error',$alert,false);
+            $ost->logError('SMTP Error', $alert, false); //NOTE: email alert overwrite - don't email when having email trouble.
             //print_r($result);
         }
 
@@ -292,6 +294,7 @@ class Email {
         //very basic checks
 
         $vars['name']=Format::striptags(trim($vars['name']));
+        $vars['email']=trim($vars['email']);
 
         if($id && $id!=$vars['id'])
             $errors['err']='Internal error. Get technical help.';
@@ -300,7 +303,7 @@ class Email {
             $errors['email']='Valid email required';
         }elseif(($eid=Email::getIdByEmail($vars['email'])) && $eid!=$id) {
             $errors['email']='Email already exits';
-        }elseif($cfg && !strcasecmp($cfg->getAdminEmail(),$vars['email'])) {
+        }elseif($cfg && !strcasecmp($cfg->getAdminEmail(), $vars['email'])) {
             $errors['email']='Email already used as admin email!';
         }elseif(Staff::getIdByEmail($vars['email'])) { //make sure the email doesn't belong to any of the staff 
             $errors['email']='Email in-use by a staff member';
diff --git a/include/class.format.php b/include/class.format.php
index a3461bf9d615c857382763c62b8ff49562352648..2c0993c459b108fdbd1bbf3394fb2e7f9ecdff95 100644
--- a/include/class.format.php
+++ b/include/class.format.php
@@ -200,7 +200,7 @@ class Format {
     }
 
     function userdate($format,$gmtime) {
-        return Format::date($format,$gmtime,$_SESSION['TZ_OFFSET'],$_SESSION['daylight']);
+        return Format::date($format,$gmtime,$_SESSION['TZ_OFFSET'],$_SESSION['TZ_DST']);
     }
     
     function date($format,$gmtimestamp,$offset=0,$daylight=false){
diff --git a/include/class.mailfetch.php b/include/class.mailfetch.php
index f25d72b26236471dd6b14e365a1745067ffe6f3e..a353b690be55c3f9cbd3740b6edcc7164dabc16e 100644
--- a/include/class.mailfetch.php
+++ b/include/class.mailfetch.php
@@ -255,7 +255,7 @@ class MailFetcher {
     }
 
     function createTicket($mid,$emailid=0){
-        global $cfg;
+        global $cfg, $ost;
 
         $mailinfo=$this->getHeaderInfo($mid);
 
@@ -265,11 +265,11 @@ class MailFetcher {
             return true;
         }
 
-	//Is the email address banned?
+	    //Is the email address banned?
         if($mailinfo['from']['email'] && EmailFilter::isBanned($mailinfo['from']['email'])) {
-	    //We need to let admin know...
-            Sys::log(LOG_WARNING,'Ticket denied','Banned email - '.$mailinfo['from']['email']);
-	    return true;
+	        //We need to let admin know...
+            $ost->logWarning('Ticket denied', 'Banned email - '.$mailinfo['from']['email']);
+	        return true;
         }
 	
 
@@ -370,15 +370,15 @@ class MailFetcher {
     }
 
     function fetchMail(){
-        global $cfg;
+        global $ost, $cfg;
       
         if(!$cfg->canFetchMail())
             return;
 
         //We require imap ext to fetch emails via IMAP/POP3
         if(!function_exists('imap_open')) {
-            $msg='PHP must be compiled with IMAP extension enabled for IMAP/POP3 fetch to work!';
-            Sys::log(LOG_WARN,'Mail Fetch Error',$msg);
+            $msg='osTicket requires PHP IMAP extension enabled for IMAP/POP3 fetch to work!';
+            $ost->logWarning('Mail Fetch Error', $msg);
             return;
         }
 
@@ -393,7 +393,7 @@ class MailFetcher {
 
         //TODO: Lock the table here??
         while($row=db_fetch_array($accounts)) {
-            $fetcher = new MailFetcher($row['userid'],Misc::decrypt($row['userpass'],SECRET_SALT),
+            $fetcher = new MailFetcher($row['userid'], Mcrypt::decrypt($row['userpass'],SECRET_SALT),
                                        $row['mail_host'],$row['mail_port'],$row['mail_protocol'],$row['mail_encryption']);
             if($fetcher->connect()){   
                 $fetcher->fetchTickets($row['email_id'],$row['mail_fetchmax'],$row['mail_delete']?true:false,$row['mail_archivefolder']);
@@ -410,7 +410,7 @@ class MailFetcher {
                         "\nError: ".$fetcher->getLastError().
                         "\n\n ".$errors.' consecutive errors. Maximum of '.$MAX_ERRORS. ' allowed'.
                         "\n\n This could be connection issues related to the host. Next delayed login attempt in aprox. 10 minutes";
-                    Sys::alertAdmin('Mail Fetch Failure Alert',$msg,true);
+                    $ost->alertAdmin('Mail Fetch Failure Alert', $msg, true);
                 }
             }
         }
diff --git a/include/class.mcrypt.php b/include/class.mcrypt.php
index a6a9791019d92ea2165b92c4ccd7e7e908380b6e..13d56a7df32e22ffe5abff5c5a6bf195cc58749d 100644
--- a/include/class.mcrypt.php
+++ b/include/class.mcrypt.php
@@ -15,20 +15,25 @@
 **********************************************************************/
 class Mcrypt {
     
-    function encrypt($text, $salt){
+    function encrypt($text, $salt) {
+        global $ost;
+        
+        //if mcrypt extension is not installed--simply return unencryted text and log a warning (if enabled).
+        if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt')) {
+            if($ost) {
+                $msg='Cryptography extension mcrypt is not enabled or installed. Important text/data is being stored as plain text in database.';
+                $ost->logWarning('mcrypt module missing', $msg);
+            }
 
-        //if mcrypt extension is not installed--simply return unencryted text and log a warning.
-        if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt')){
-            $msg='Cryptography extension mcrypt is not enabled or installed. Important text/data is being stored as plain text in database.';
-            Sys::log(LOG_WARN,'mcrypt module missing',$msg);
             return $text;
         }
 
-        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$salt, $text, MCRYPT_MODE_ECB,
+        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB,
                          mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
     }
 
-    function decrypt($text, $salt){
+    function decrypt($text, $salt) {
+
         if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt'))
             return $text;
 
diff --git a/include/class.misc.php b/include/class.misc.php
index d9f59f47858b23c9c47c2de6ea6c3cedfda61df1..409e4bac6f84eee1c73b1d040eda18455c0f4954 100644
--- a/include/class.misc.php
+++ b/include/class.misc.php
@@ -29,27 +29,6 @@ class Misc {
         return mt_rand($start,$end);
     }
 
-    function encrypt($text, $salt) {
-
-        //if mcrypt extension is not installed--simply return unencryted text and log a warning.
-        if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt')) {
-            $msg='Cryptography extension mcrypt is not enabled or installed. IMAP/POP passwords are being stored as plain text in database.';
-            Sys::log(LOG_WARN,'mcrypt missing',$msg);
-            return $text;
-        }
-
-        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$salt, $text, MCRYPT_MODE_ECB,
-                         mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
-    }
-
-    function decrypt($text, $salt) {
-        if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt'))
-            return $text;
-
-        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB,
-                        mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
-    }
-
     /* misc date helpers...this will go away once we move to php 5 */ 
     function db2gmtime($var){
         global $cfg;
@@ -67,7 +46,7 @@ class Misc {
             $time=Misc::gmtime(); //gm time.
         else{ //user time to GM.
             $time=is_int($var)?$var:strtotime($var);
-            $offset=$_SESSION['TZ_OFFSET']+($_SESSION['daylight']?date('I',$time):0);
+            $offset=$_SESSION['TZ_OFFSET']+($_SESSION['TZ_DST']?date('I',$time):0);
             $time=$time-($offset*3600);
         }
         //gm to db time
diff --git a/include/class.osticket.php b/include/class.osticket.php
new file mode 100644
index 0000000000000000000000000000000000000000..eb1b0361971176c00673ee61a0f23f1c17f0fa7e
--- /dev/null
+++ b/include/class.osticket.php
@@ -0,0 +1,228 @@
+<?php
+/*************************************************************************
+    class.osticket.php
+
+    osTicket (sys) -> Config.
+
+    Core osTicket object: loads congfig and provides loggging facility.
+
+    Use osTicket::start(configId)
+
+    Peter Rotich <peter@osticket.com>
+    Copyright (c)  2006-2012 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:
+**********************************************************************/
+
+require_once(INCLUDE_DIR.'class.config.php'); //Config helper
+define('LOG_WARN',LOG_WARNING);
+
+class osTicket {
+
+    var $loglevel=array(1=>'Error','Warning','Debug');
+    var $errors;
+    var $warning;
+    var $message;
+
+    var $headers;
+
+    var $config;
+    var $session;
+
+    function osTicket($cfgId) {
+        $this->config = Config::lookup($cfgId);
+        $this->session = osTicketSession::start(SESSION_TTL); // start_session 
+    }
+
+    function isSystemOnline() {
+        return ($this->getConfig() && $this->getConfig()->isHelpdeskOnline() && !$this->isUpgradePending());
+    }
+
+    function isUpgradePending() {
+        return (defined('SCHEMA_SIGNATURE') && strcasecmp($this->getConfig()->getSchemaSignature(), SCHEMA_SIGNATURE));
+    }
+
+    function getSession() {
+        return $this->session;
+    }
+
+    function getConfig() {
+        return $this->config;
+    }
+
+    function getConfigId() {
+
+        return $this->getConfig()?$this->getConfig()->getId():0;
+    }
+
+    function addExtraHeader($header) {
+        $this->headers[md5($header)] = $header;
+    }
+
+    function getExtraHeaders() {
+        return $this->headers;
+    }
+
+    function getErrors() {
+        return $this->errors;
+    }
+
+    function setErrors($errors) {
+        if(!is_array($errors))
+            return  $this->setError($errors);
+
+        $this->errors = $errors;
+    }
+
+    function getError() {
+        return $this->errors['err'];
+    }
+
+    function setError($error) {
+        $this->errors['err'] = $error;
+    }
+
+    function clearError() {
+        $this->setError('');
+    }
+
+    function getWarning() {
+        return $this->warning;
+    }
+
+    function setWarning($warn) {
+        $this->warning = $warn;
+    }
+
+    function clearWarning() {
+        $this->setWarning('');
+    }
+
+
+    function getMessage() {
+        return $this->message;
+    }
+
+    function setMessage($msg) {
+        $this->message = $msg;
+    }
+
+    function clearMessage() {
+        $this->setMessage('');
+    }
+
+
+    function alertAdmin($subject, $message, $log=false) {
+                
+        //Set admin's email address
+        if(!($to=$this->getConfig()->getAdminEmail()))
+            $to=ADMIN_EMAIL;
+
+        //Try getting the alert email.
+        $email=null;
+        if(!($email=$this->getConfig()->getAlertEmail())) 
+            $email=$this->getConfig()->getDefaultEmail(); //will take the default email.
+
+        if($email) {
+            $email->send($to, $subject, $message);
+        } else {//no luck - try the system mail.
+            Email::sendmail($to, $subject, $message, sprintf('"osTicket Alerts"<%s>',$to));
+        }
+
+        //log the alert? Watch out for loops here.
+        if($log)
+            $this->log(LOG_CRIT, $subject, $message, false); //Log the entry...and make sure no alerts are resent.
+
+    }
+
+    function logDebug($title, $message, $alert=false) {
+        return $this->log(LOG_DEBUG, $title, $message, $alert);
+    }
+
+    function logInfo($title, $message, $alert=false) {
+        return $this->log(LOG_INFO, $title, $message, $alert);
+    }
+
+    function logWarning($title, $message, $alert=true) {
+        return $this->log(LOG_WARN, $title, $message, $alert);
+    }
+    
+    function logError($title, $error, $alert=true) {
+        return $this->log(LOG_ERR, $title, $error, $alert);
+    }
+
+    function log($priority, $title, $message, $alert=false) {
+
+        //We are providing only 3 levels of logs. Windows style.
+        switch($priority) {
+            case LOG_EMERG:
+            case LOG_ALERT: 
+            case LOG_CRIT: 
+            case LOG_ERR:
+                $level=1; //Error
+                break;
+            case LOG_WARN:
+            case LOG_WARNING:
+                $level=2; //Warning
+                break;
+            case LOG_NOTICE:
+            case LOG_INFO:
+            case LOG_DEBUG:
+            default:
+                $level=3; //Debug
+        }
+
+        //Alert admin if enabled...
+        if($alert)
+            $this->alertAdmin($title, $message);
+
+
+        if($this->getConfig()->getLogLevel()<$level)
+            return false;
+
+        //Save log based on system log level settings.
+        $loglevel=array(1=>'Error','Warning','Debug');
+        $sql='INSERT INTO '.SYSLOG_TABLE.' SET created=NOW(), updated=NOW() '.
+            ',title='.db_input($title).
+            ',log_type='.db_input($loglevel[$level]).
+            ',log='.db_input($message).
+            ',ip_address='.db_input($_SERVER['REMOTE_ADDR']);
+        
+        mysql_query($sql); //don't use db_query to avoid possible loop.
+        
+        return true;
+    }
+
+    function purgeLogs() {
+
+        if(!($gp=$this->getConfig()->getLogGracePeriod()) || !is_numeric($gp))
+            return false;
+
+        //System logs
+        $sql='DELETE  FROM '.SYSLOG_TABLE.' WHERE DATE_ADD(created, INTERVAL '.$gp.' MONTH)<=NOW()';
+        db_query($sql);
+        
+        //TODO: Activity logs
+
+        return true;
+    }
+
+    /**** static functions ****/
+    function start($configId) {
+
+        if(!$configId || !($ost = new osTicket($configId)) || $ost->getConfigId()!=$configId)
+            return null;
+
+        //Set default time zone... user/staff settting will overwrite it (on login).
+        $_SESSION['TZ_OFFSET'] = $ost->getConfig()->getTZoffset();
+        $_SESSION['TZ_DST'] = $ost->getConfig()->observeDaylightSaving();
+
+        return $ost;
+    }
+}
+
+?>
diff --git a/include/class.ostsession.php b/include/class.ostsession.php
index ccbae6e03f90147f06b24a79b0e1468faae4f821..0bcd9449fb234c6b9a895da6b046527f7a7909a4 100644
--- a/include/class.ostsession.php
+++ b/include/class.ostsession.php
@@ -53,9 +53,11 @@ class osTicketSession {
         return (true);
     }
  
-    function read($session_id){
+    function read($id){
         $data="";
-        $sql='SELECT session_data FROM '.SESSION_TABLE.' WHERE session_id='.db_input($session_id).' AND session_expire>NOW()';
+        $sql='SELECT session_data FROM '.SESSION_TABLE
+            .' WHERE session_id='.db_input($id)
+            .'  AND session_expire>NOW()';
         if(($res=db_query($sql)) && db_num_rows($res))
             list($data)=db_fetch_row($res);
 
@@ -63,7 +65,7 @@ class osTicketSession {
     }
 
     function write($id, $data){
-        global $cfg,$thisstaff;
+        global $thisstaff;
 
         $sql='REPLACE INTO '.SESSION_TABLE.' SET session_updated=NOW() '.
              ',session_id='.db_input($id).
@@ -98,8 +100,9 @@ class osTicketSession {
             $sql.=" AND TIME_TO_SEC(TIMEDIFF(NOW(),session_updated))<$sec";
 
         $users=array();
-        if(($res=db_query($sql)) && db_num_rows($res)){
-            list($users[])=db_fetch_row($res);
+        if(($res=db_query($sql)) && db_num_rows($res)) {
+            while(list($uid)=db_fetch_row($res))
+                $users[] = $uid;
         }
 
         return $users;
diff --git a/include/class.staff.php b/include/class.staff.php
index 00554157935ba0d82aa77596bf9c912f0fcf5ad5..bd7379ed95e659fbf0c2c527735376f831238e89 100644
--- a/include/class.staff.php
+++ b/include/class.staff.php
@@ -95,7 +95,8 @@ class Staff {
     /* check if passwd reset is due. */
     function isPasswdResetDue() {
         global $cfg;
-        return ($cfg && $cfg->getPasswdResetPeriod() && $this->ht['passwd_change_sec']>($cfg->getPasswdResetPeriod()*30*24*60*60));
+        return ($cfg && $cfg->getPasswdResetPeriod() 
+                    && $this->ht['passwd_change_sec']>($cfg->getPasswdResetPeriod()*30*24*60*60));
     }
 
     function isPasswdChangeDue() {
@@ -495,7 +496,7 @@ class Staff {
     }
 
     function login($username, $passwd, &$errors, $strike=true) {
-        global $cfg, $session;
+        global $ost, $cfg;
 
 
         if($_SESSION['_staff']['laststrike']) {
@@ -520,13 +521,16 @@ class Staff {
             $_SESSION['_staff']['userID']=$username;
             $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.
+            $_SESSION['TZ_DST']=$user->observeDaylight();
+
+            $ost->logDebug('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.
-            if($session && is_object($session) && $sid)
+            if(($session=$ost->getSession()) && is_object($session) && $sid)
                 $session->destroy($sid);
+
             session_write_close();
         
             return $user;
@@ -540,12 +544,12 @@ 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()));
+            $ost->logWarning('Excessive login attempts ('.$_POST['username'].')', $alert, ($cfg->alertONLoginError()));
     
         } 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);
+            $ost->logWarning('Failed staff login attempt ('.$_POST['username'].')', $alert, false);
         }
 
         return false;
diff --git a/include/class.sys.php b/include/class.sys.php
deleted file mode 100644
index 33b5c830407f1b56fb1ef8eff47657e1296bb97a..0000000000000000000000000000000000000000
--- a/include/class.sys.php
+++ /dev/null
@@ -1,107 +0,0 @@
-<?php
-/*************************************************************************
-    class.sys.php
-
-    System core helper.
-
-    Peter Rotich <peter@osticket.com>
-    Copyright (c)  2006-2012 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:
-**********************************************************************/
-
-require_once(INCLUDE_DIR.'class.config.php'); //Config helper
-
-define('LOG_WARN',LOG_WARNING);
-
-class Sys {
-
-    var $loglevel=array(1=>'Error','Warning','Debug');
-
-
-    //Load configuration info.
-    function getConfig() {
-        $cfg= new Config(1);
-        return ($cfg && $cfg->getId())?$cfg:null;
-    }
-
-
-    function alertAdmin($subject,$message,$log=false) {
-        global $cfg;
-                
-        //Set admin's email address
-        if(!$cfg || !($to=$cfg->getAdminEmail()))
-            $to=ADMIN_EMAIL;
-
-        //Try getting the alert email.
-        $email=null;
-        if($cfg && !($email=$cfg->getAlertEmail())) 
-            $email=$cfg->getDefaultEmail(); //will take the default email.
-
-        if($email) {
-            $email->send($to,$subject,$message);
-        }else {//no luck - try the system mail.
-            Email::sendmail($to,$subject,$message,sprintf('"osTicket Alerts"<%s>',$to));
-        }
-
-        //log the alert? Watch out for loops here.
-        if($log && is_object($cfg)) { //if $cfg is not set then it means we don't have DB connection.
-            Sys::log(LOG_CRIT,$subject,$message,false); //Log the entry...and make sure no alerts are resent.
-        }
-
-    }
-
-    function log($priority,$title,$message,$alert=true) {
-        global $cfg;
-
-        switch($priority){ //We are providing only 3 levels of logs. Windows style.
-            case LOG_EMERG:
-            case LOG_ALERT: 
-            case LOG_CRIT: 
-            case LOG_ERR:
-                $level=1;
-                if($alert) {
-                    Sys::alertAdmin($title,$message);
-                }
-                break;
-            case LOG_WARN:
-            case LOG_WARNING:
-                //Warning...
-                $level=2;
-                break;
-            case LOG_NOTICE:
-            case LOG_INFO:
-            case LOG_DEBUG:
-            default:
-                $level=3;
-                //debug
-        }
-        //Save log based on system log level settings.
-        if($cfg && $cfg->getLogLevel()>=$level){
-            $loglevel=array(1=>'Error','Warning','Debug');
-            $sql='INSERT INTO '.SYSLOG_TABLE.' SET created=NOW(),updated=NOW() '.
-                 ',title='.db_input($title).
-                 ',log_type='.db_input($loglevel[$level]).
-                 ',log='.db_input($message).
-                 ',ip_address='.db_input($_SERVER['REMOTE_ADDR']);
-            //echo $sql;
-            mysql_query($sql); //don't use db_query to avoid possible loop.
-        }
-    }
-
-    function purgeLogs(){
-        global $cfg;
-
-        if($cfg && ($gp=$cfg->getLogGracePeriod()) && is_numeric($gp)) {
-            $sql='DELETE  FROM '.SYSLOG_TABLE.' WHERE DATE_ADD(created, INTERVAL '.$gp.' MONTH)<=NOW()';
-            db_query($sql);
-        }
-
-    }
-}
-
-?>
diff --git a/include/class.template.php b/include/class.template.php
index 36d9b2f4845d3ca14ad564c9a8c829c11b9ab083..fa8d070d544c4bf5eda0da758fed814f106c529d 100644
--- a/include/class.template.php
+++ b/include/class.template.php
@@ -91,11 +91,12 @@ class Template {
         return (db_query($sql) && db_affected_rows());
     }
 
-    function getMsgTemplate($name){
+    function getMsgTemplate($name) {
+        global $ost;
 
         //TODO: Don't preload - do ondemand fetch!
         $tpl=array();
-        switch(strtolower($name)){
+        switch(strtolower($name)) {
             case 'ticket_autoresp':
                  $tpl=array('subj'=>$this->ht['ticket_autoresp_subj'],'body'=>$this->ht['ticket_autoresp_body']);
                  break;
@@ -130,7 +131,7 @@ class Template {
                  $tpl=array('subj'=>$this->ht['ticket_overdue_subj'],'body'=>$this->ht['ticket_overdue_body']);
                  break;
             default:
-                 Sys::log(LOG_WARNING,'Template Fetch Error',"Unable to fetch '$name' template - id #".$this->getId());
+                 $ost->logWarning('Template Fetch Error', "Unable to fetch '$name' template - id #".$this->getId());
                  $tpl=array();
         }
 
@@ -197,7 +198,7 @@ class Template {
         if($errors) return false;
 
         $sql='UPDATE '.EMAIL_TEMPLATE_TABLE.' SET updated=NOW() ';
-        switch(strtolower($vars['tpl'])){
+        switch(strtolower($vars['tpl'])) {
             case 'ticket_autoresp':
                 $sql.=',ticket_autoresp_subj='.db_input($vars['subj']).',ticket_autoresp_body='.db_input($vars['body']);
                 break;
@@ -326,8 +327,8 @@ class Template {
         return ($id && is_numeric($id) && ($t= new Template($id)) && $t->getId()==$id)?$t:null;
     }
 
-    function save($id,$vars,&$errors) {
-        global $cfg;
+    function save($id, $vars, &$errors) {
+        global $ost;
 
         $tpl=null;
         $vars['name']=Format::striptags(trim($vars['name']));
@@ -354,12 +355,14 @@ class Template {
             $sql='UPDATE '.EMAIL_TEMPLATE_TABLE.' SET '.$sql.' WHERE tpl_id='.db_input($id);
             if(db_query($sql))
                 return true;
+
             $errors['err']='Unable to update the template. Internal error occurred';
-        }elseif($tpl && ($info=$tpl->getInfo())){
+        
+        } elseif($tpl && ($info=$tpl->getInfo())) {
 
             $sql='INSERT INTO '.EMAIL_TEMPLATE_TABLE.' SET '.$sql
                 .' ,created=NOW() '
-                .' ,cfg_id='.db_input($cfg->getId())
+                .' ,cfg_id='.db_input($ost->getConfigId())
                 .' ,ticket_autoresp_subj='.db_input($info['ticket_autoresp_subj'])
                 .' ,ticket_autoresp_body='.db_input($info['ticket_autoresp_body'])
                 .' ,ticket_notice_subj='.db_input($info['ticket_notice_subj'])
diff --git a/include/class.ticket.php b/include/class.ticket.php
index 2fd5d4f29c8a049659a04f9b7a8365be626bb436..130ccb6fa15d42655dba83ef4f677014ceda9b2a 100644
--- a/include/class.ticket.php
+++ b/include/class.ticket.php
@@ -885,11 +885,11 @@ class Ticket{
     }
 
     function onOpenLimit($sendNotice=true) {
-        global $cfg;
+        global $ost, $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);
+        $ost->logWarning('Max. Open Tickets Limit ('.$this->getEmail().')', $msg);
 
         if(!$sendNotice || !$cfg->sendOverLimitNotice()) return true;
 
@@ -916,7 +916,7 @@ class Ticket{
             .'Open ticket: '.$client->getNumOpenTickets()."\n"
             .'Max Allowed: '.$cfg->getMaxOpenTickets()."\n\nNotice sent to the user.";
             
-        Sys::alertAdmin('Overlimit Notice',$msg);
+        $ost->alertAdmin('Overlimit Notice', $msg);
        
         return true;
     }
@@ -1808,7 +1808,7 @@ class Ticket{
      *  $autorespond and $alertstaff overwrites config settings...
      */      
     function create($vars, &$errors, $origin, $autorespond=true, $alertstaff=true) {
-        global $cfg,$thisclient,$_FILES;
+        global $ost, $cfg, $thisclient, $_FILES;
 
         //Check for 403
         if ($vars['email']  && Validator::is_email($vars['email'])) {
@@ -1816,7 +1816,7 @@ class Ticket{
             //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']);
+                $ost->logWarning('Ticket denied', 'Banned email - '.$vars['email']);
                 return 0;
             }
 
@@ -1827,8 +1827,9 @@ class Ticket{
                     && ($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']));
+                $ost->logWarning('Ticket denied -'.$vars['email'], 
+                        sprintf('Max open tickets (%d) reached for %s ', 
+                            $cfg->getMaxOpenTickets(), $vars['email']));
 
                 return 0;
             }
@@ -1837,9 +1838,10 @@ class Ticket{
         if (($email_filter=new EmailFilter($vars))
                 && ($filter=$email_filter->shouldReject())) {
             $errors['err']='Ticket denied. Error #403';
-            Sys::log(LOG_WARNING,'Ticket denied',
-                sprintf('Banned email - %s by filter "%s"', $vars['email'],
-                    $filter->getName()));
+            $ost->logWarning('Ticket denied', 
+                    sprintf('Banned email - %s by filter "%s"', 
+                        $vars['email'], $filter->getName()));
+
             return 0;
         }
 
diff --git a/include/mysql.php b/include/mysql.php
index 47f5ab5c8854e7ce4f6cdea47cd5ebd7dccd2fc4..85be9829966500b99fecb4714cb3be53e09c41ec 100644
--- a/include/mysql.php
+++ b/include/mysql.php
@@ -16,8 +16,6 @@
     vim: expandtab sw=4 ts=4 sts=4:
 **********************************************************************/
 
-    require_once(INCLUDE_DIR.'class.sys.php');
-
     function db_connect($host, $user, $passwd, $db = "") {
         
         //Assert
@@ -53,7 +51,11 @@
 
         return $version;
     }
-    
+
+    function db_timezone() {
+        return db_get_variable('time_zone');
+    }
+
     function db_get_variable($variable, $type='session') {
         $sql =sprintf('SELECT @@%s.%s',$type,$variable);
         return db_result(db_query($sql));
@@ -74,18 +76,18 @@
     }
    
 	// execute sql query
-	function db_query($query, $database="",$conn=""){
-        global $cfg;
+	function db_query($query, $database="", $conn=""){
+        global $ost;
        
 		if($conn) { /* connection is provided*/
-            $result = ($database)?mysql_db_query($database,$query,$conn):mysql_query($query,$conn);
+            $result = ($database)?mysql_db_query($database, $query, $conn):mysql_query($query, $conn);
    	    } else {
-            $result = ($database)?mysql_db_query($database,$query):mysql_query($query);
+            $result = ($database)?mysql_db_query($database, $query):mysql_query($query);
    	    }
                 
-        if(!$result) { //error reporting
+        if(!$result && $ost) { //error reporting
             $alert='['.$query.']'."\n\n".db_error();
-            Sys::log(LOG_ALERT,'DB Error #'.db_errno(),$alert,($cfg && $cfg->alertONSQLError()));
+            $ost->logError('DB Error #'.db_errno(), $alert, ($ost->alertONSQLError()));
             //echo $alert; #uncomment during debuging or dev.
         }
 
diff --git a/include/staff/attachment.inc.php b/include/staff/attachment.inc.php
index 5951b87c0b0788767b34c98d1a7290a7c1debcdd..6027678123ca55684c721ae72f98133135f603f7 100644
--- a/include/staff/attachment.inc.php
+++ b/include/staff/attachment.inc.php
@@ -1,7 +1,7 @@
 <?php
 if(!defined('OSTADMININC') || !$thisstaff->isAdmin()) die('Access Denied');
 //Get the config info.
-$config=($errors && $_POST)?Format::input($_POST):$cfg->getConfig();
+$config=($errors && $_POST)?Format::input($_POST):$cfg->getConfigInfo();
 ?>
 <table width="100%" border="0" cellspacing=0 cellpadding=0>
     <form action="admin.php?t=attach" method="post">
diff --git a/include/staff/editticket.inc.php b/include/staff/editticket.inc.php
deleted file mode 100644
index 20accf0e4d70883861b51e2c6518fa6bce060cdc..0000000000000000000000000000000000000000
--- a/include/staff/editticket.inc.php
+++ /dev/null
@@ -1,142 +0,0 @@
-<?php
-if(!defined('OSTSCPINC') || !is_object($ticket) || !is_object($thisstaff) || !$thisstaff->isStaff()) die('Access Denied');
-
-if(!($thisstaff->canEditTickets() || ($thisstaff->isManager() && $ticket->getDeptId()==$thisstaff->getDeptId()))) die('Access Denied. Perm error.');
-
-if($_POST && $errors){
-    $info=Format::input($_POST);
-}else{
-    $info=array('email'=>$ticket->getEmail(),
-                'name' =>$ticket->getName(),
-                'phone'=>$ticket->getPhone(),
-                'phone_ext'=>$ticket->getPhoneExt(),
-                'pri'=>$ticket->getPriorityId(),
-                'topicId'=>$ticket->getTopicId(),
-                'topic'=>$ticket->getHelpTopic(),
-                'subject' =>$ticket->getSubject(),
-                'duedate' =>$ticket->getDueDate()?(Format::userdate('m/d/Y',Misc::db2gmtime($ticket->getDueDate()))):'',
-                'time'=>$ticket->getDueDate()?(Format::userdate('G:i',Misc::db2gmtime($ticket->getDueDate()))):'',
-                );
-    /*Note: Please don't make me explain how dates work - it is torture. Trust me! */
-}
-
-?>
-<div width="100%">
-    <?php if($errors['err']) { ?>
-        <p align="center" id="errormessage"><?php echo $errors['err']; ?></p>
-    <?php }elseif($msg) { ?>
-        <p align="center" class="infomessage"><?php echo $msg; ?></p>
-    <?php }elseif($warn) { ?>
-        <p class="warnmessage"><?php echo $warn; ?></p>
-    <?php } ?>
-</div>
-<table width="100%" border="0" cellspacing=1 cellpadding=2>
-  <form action="tickets.php?id=<?php echo $ticket->getId(); ?>" method="post">
-    <input type='hidden' name='id' value='<?php echo $ticket->getId(); ?>'>
-    <input type='hidden' name='a' value='update'>
-    <tr><td align="left" colspan=2 class="msg">
-        Update Ticket #<?php echo $ticket->getExtId(); ?>&nbsp;&nbsp;(<a href="tickets.php?id=<?php echo $ticket->getId(); ?>" style="color:black;">View Ticket</a>)<br></td></tr>
-    <tr>
-        <td align="left" nowrap width="120"><b>Email Address:</b></td>
-        <td>
-            <input type="text" id="email" name="email" size="25" value="<?php echo $info['email']; ?>">
-            &nbsp;<font class="error"><b>*</b>&nbsp;<?php echo $errors['email']; ?></font>
-        </td>
-    </tr>
-    <tr>
-        <td align="left" ><b>Full Name:</b></td>
-        <td>
-            <input type="text" id="name" name="name" size="25" value="<?php echo $info['name']; ?>">
-            &nbsp;<font class="error"><b>*</b>&nbsp;<?php echo $errors['name']; ?></font>
-        </td>
-    </tr>
-    <tr>
-        <td align="left"><b>Subject:</b></td>
-        <td>
-            <input type="text" name="subject" size="35" value="<?php echo $info['subject']; ?>">
-            &nbsp;<font class="error">*&nbsp;<?php echo $errors['subject']; ?></font>
-        </td>
-    </tr>
-    <tr>
-        <td align="left">Telephone:</td>
-        <td><input type="text" name="phone" size="25" value="<?php echo $info['phone']; ?>">
-             &nbsp;Ext&nbsp;<input type="text" name="phone_ext" size="6" value="<?php echo $info['phone_ext']; ?>">
-            &nbsp;<font class="error">&nbsp;<?php echo $errors['phone']; ?></font></td>
-    </tr>
-    <tr height=1px><td align="left" colspan=2 >&nbsp;</td></tr>
-    <tr>
-        <td align="left" valign="top">Due Date:</td>
-        <td>
-            <i>Time is based on your time zone (GM <?php echo $thisstaff->getTZoffset(); ?>)</i>&nbsp;<font class="error">&nbsp;<?php echo $errors['time']; ?></font><br>
-            <input id="duedate" name="duedate" value="<?php echo Format::htmlchars($info['duedate']); ?>"
-                onclick="event.cancelBubble=true;calendar(this);" autocomplete=OFF>
-            <a href="#" onclick="event.cancelBubble=true;calendar(getObj('duedate')); return false;"><img src='images/cal.png'border=0 alt=""></a>
-            &nbsp;&nbsp;
-            <?php
-             $min=$hr=null;
-             if($info['time'])
-                list($hr,$min)=explode(':',$info['time']);
-                echo Misc::timeDropdown($hr,$min,'time');
-            ?>
-            &nbsp;<font class="error">&nbsp;<?php echo $errors['duedate']; ?></font>
-        </td>
-    </tr>
-    <?php
-      $sql='SELECT priority_id,priority_desc FROM '.TICKET_PRIORITY_TABLE.' ORDER BY priority_urgency DESC';
-      if(($priorities=db_query($sql)) && db_num_rows($priorities)){ ?>
-      <tr>
-        <td align="left">Priority:</td>
-        <td>
-            <select name="pri">
-              <?php
-                while($row=db_fetch_array($priorities)){ ?>
-                    <option value="<?php echo $row['priority_id']; ?>" <?php echo $info['pri']==$row['priority_id']?'selected':''; ?> ><?php echo $row['priority_desc']; ?></option>
-              <?php } ?>
-            </select>
-        </td>
-       </tr>
-    <?php } ?>
-
-    <?php
-    $services= db_query('SELECT topic_id,topic,isactive FROM '.TOPIC_TABLE.' ORDER BY topic');
-    if($services && db_num_rows($services)){ ?>
-    <tr>
-        <td align="left" valign="top">Help Topic:</td>
-        <td>
-            <select name="topicId">    
-                <option value="0" selected >None</option>
-                <?php if(!$info['topicId'] && $info['topic']){ //old helptopic ?>
-                <option value="0" selected ><?php echo $info['topic']; ?> (deleted)</option>
-                <?php
-                }
-                 while (list($topicId,$topic,$active) = db_fetch_row($services)){
-                    $selected = ($info['topicId']==$topicId)?'selected':'';
-                    $status=$active?'Active':'Inactive';
-                    ?>
-                    <option value="<?php echo $topicId; ?>"<?php echo $selected; ?>><?php echo $topic; ?>&nbsp;&nbsp;&nbsp;(<?php echo $status; ?>)</option>
-                <?php
-                 } ?>
-            </select>
-            &nbsp;(optional)<font class="error">&nbsp;<?php echo $errors['topicId']; ?></font>
-        </td>
-    </tr>
-    <?php
-    } ?>
-    <tr>
-        <td align="left" valign="top"><b>Internal Note:</b></td>
-        <td>
-            <i>Reasons for the edit.</i><font class="error"><b>*&nbsp;<?php echo $errors['note']; ?></b></font><br/>
-            <textarea name="note" cols="45" rows="5" wrap="soft"><?php echo $info['note']; ?></textarea></td>
-    </tr>
-    <tr height=2px><td align="left" colspan=2 >&nbsp;</td></tr>
-    <tr>
-        <td></td>
-        <td>
-            <input class="button" type="submit" name="submit_x" value="Update Ticket">
-            <input class="button" type="reset" value="Reset">
-            <input class="button" type="button" name="cancel" value="Cancel" onClick='window.location.href="tickets.php?id=<?php echo $ticket->getId(); ?>"'>    
-        </td>
-    </tr>
-  </form>
-</table>
-
diff --git a/include/staff/header.inc.php b/include/staff/header.inc.php
index b0a7c4efef46bfa5ce923ac251beb101c3125293..c48ee8b360070be6f82cf74e073f8122aa0ff897 100644
--- a/include/staff/header.inc.php
+++ b/include/staff/header.inc.php
@@ -1,86 +1,88 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
-    <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">
-        .tip_shadow { display:block !important; }
-    </style>
-    <![endif]-->
-    <script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
-    <script type="text/javascript" src="./js/calendar.js"></script>
-    <script type="text/javascript" src="./js/tips.js"></script>
-    <script type="text/javascript" src="./js/nicEdit.js"></script>
-    <script type="text/javascript" src="./js/bootstrap-typeahead.js"></script>
-    <script type="text/javascript" src="./js/scp.js"></script>
-    <link rel="stylesheet" href="./css/scp.css" media="screen">
-    <link rel="stylesheet" href="./css/typeahead.css" media="screen">
-</head>
-<body>
-<div id="container">
-    <div id="header">
-        <a href="index.php" id="logo">osTicket - Customer Support System</a>
-        <p id="info">Welcome back, <strong><?php echo $thisstaff->getUserName(); ?></strong>
-           <?php
-            if($thisstaff->isAdmin() && !defined('ADMINPAGE')) { ?>
-            | <a href="admin.php">Admin Panel</a>
-            <?php }else{ ?>
-            | <a href="index.php">Staff Panel</a>
-            <?php } ?>
-            | <a href="profile.php">My Preferences</a> | <a href="logout.php">Log Out</a>
-        </p>
-    </div>
-    <ul id="nav">
-        <?php
-        if(($tabs=$nav->getTabs()) && is_array($tabs)){
-            foreach($tabs as $name =>$tab) {
-                echo sprintf('<li class="%s"><a href="%s">%s</a>',$tab['active']?'active':'inactive',$tab['href'],$tab['desc']);
-                if(!$tab['active'] && ($subnav=$nav->getSubMenu($name))){
-                    echo "<ul>\n";
-                    foreach($subnav as $item) {
-                        echo sprintf('<li><a class="%s" href="%s" title="%s" >%s</a></li>',
-                                $item['iconclass'],$item['href'],$item['title'],$item['desc']);
-                    }
-                    echo "\n</ul>\n";
-                }
-                echo "\n</li>\n";
-            }
-        } ?>
-    </ul>
-    <ul id="sub_nav">
-        <?php
-        if(($subnav=$nav->getSubMenu()) && is_array($subnav)){
-            $activeMenu=$nav->getActiveMenu();
-            if($activeMenu>0 && !isset($subnav[$activeMenu-1]))
-                $activeMenu=0;
-            foreach($subnav as $k=> $item) {
-                if($item['droponly']) continue;
-                $class=$item['iconclass'];
-                if ($activeMenu && $k+1==$activeMenu 
-                        or (!$activeMenu 
-                            && (strpos(strtoupper($item['href']),strtoupper(basename($_SERVER['SCRIPT_NAME']))) !== false
-                                or ($item['urls']
-                                    && in_array(basename($_SERVER['SCRIPT_NAME']),$item['urls'])
-                                    )
-                                )))
-                    $class="$class active";
-
-                echo sprintf('<li><a class="%s" href="%s" title="%s" >%s</a></li>',$class,$item['href'],$item['title'],$item['desc']);
-            }
-        }
-        ?>
-    </ul>
-    <div id="content">
-        <?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 } ?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <title>osTicket Staff Control Panel</title>
+    <!--[if IE]>
+    <style type="text/css">
+        .tip_shadow { display:block !important; }
+    </style>
+    <![endif]-->
+    <script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
+    <script type="text/javascript" src="../js/jquery-ui-1.8.18.custom.min.js"></script>
+    <script type="text/javascript" src="./js/tips.js"></script>
+    <script type="text/javascript" src="./js/nicEdit.js"></script>
+    <script type="text/javascript" src="./js/bootstrap-typeahead.js"></script>
+    <script type="text/javascript" src="./js/scp.js"></script>
+    <link rel="stylesheet" href="./css/scp.css" media="screen">
+    <link rel="stylesheet" href="./css/typeahead.css" media="screen">
+    <link type="text/css" href="../css/ui-lightness/jquery-ui-1.8.18.custom.css" rel="stylesheet" />   
+    <?php
+    if($ost && ($headers=$ost->getExtraHeaders())) {
+        echo "\n\t".implode("\n\t", $headers)."\n";
+    }
+    ?>
+</head>
+<body>
+<div id="container">
+    <div id="header">
+        <a href="index.php" id="logo">osTicket - Customer Support System</a>
+        <p id="info">Howdy, <strong><?php echo $thisstaff->getUserName(); ?></strong>
+           <?php
+            if($thisstaff->isAdmin() && !defined('ADMINPAGE')) { ?>
+            | <a href="admin.php">Admin Panel</a>
+            <?php }else{ ?>
+            | <a href="index.php">Staff Panel</a>
+            <?php } ?>
+            | <a href="profile.php">My Preferences</a> | <a href="logout.php">Log Out</a>
+        </p>
+    </div>
+    <ul id="nav">
+        <?php
+        if(($tabs=$nav->getTabs()) && is_array($tabs)){
+            foreach($tabs as $name =>$tab) {
+                echo sprintf('<li class="%s"><a href="%s">%s</a>',$tab['active']?'active':'inactive',$tab['href'],$tab['desc']);
+                if(!$tab['active'] && ($subnav=$nav->getSubMenu($name))){
+                    echo "<ul>\n";
+                    foreach($subnav as $item) {
+                        echo sprintf('<li><a class="%s" href="%s" title="%s" >%s</a></li>',
+                                $item['iconclass'],$item['href'],$item['title'],$item['desc']);
+                    }
+                    echo "\n</ul>\n";
+                }
+                echo "\n</li>\n";
+            }
+        } ?>
+    </ul>
+    <ul id="sub_nav">
+        <?php
+        if(($subnav=$nav->getSubMenu()) && is_array($subnav)){
+            $activeMenu=$nav->getActiveMenu();
+            if($activeMenu>0 && !isset($subnav[$activeMenu-1]))
+                $activeMenu=0;
+            foreach($subnav as $k=> $item) {
+                if($item['droponly']) continue;
+                $class=$item['iconclass'];
+                if ($activeMenu && $k+1==$activeMenu 
+                        or (!$activeMenu 
+                            && (strpos(strtoupper($item['href']),strtoupper(basename($_SERVER['SCRIPT_NAME']))) !== false
+                                or ($item['urls']
+                                    && in_array(basename($_SERVER['SCRIPT_NAME']),$item['urls'])
+                                    )
+                                )))
+                    $class="$class active";
+
+                echo sprintf('<li><a class="%s" href="%s" title="%s" >%s</a></li>',$class,$item['href'],$item['title'],$item['desc']);
+            }
+        }
+        ?>
+    </ul>
+    <div id="content">
+        <?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 } ?>
+
diff --git a/include/staff/preference.inc.php b/include/staff/preference.inc.php
index 054d592a7555f8d16f436f9cc5c9c66a91b6f27b..6eb27354b0d4cd019964b460b58a3c4b0db1110e 100644
--- a/include/staff/preference.inc.php
+++ b/include/staff/preference.inc.php
@@ -2,7 +2,7 @@
 if(!defined('OSTADMININC') || !$thisstaff->isAdmin()) die('Access Denied');
 
 //Get the config info.
-$config=($errors && $_POST)?Format::input($_POST):Format::htmlchars($cfg->getConfig());
+$config=($errors && $_POST)?Format::input($_POST):Format::htmlchars($cfg->getConfigInfo());
 //Basic checks for warnings...
 $warn=array();
 if($config['allow_attachments'] && !$config['upload_dir']) {
diff --git a/include/staff/syslogs.inc.php b/include/staff/syslogs.inc.php
index 5418518f71f498996aee68cd2a6f0b5a8f7b4034..e0f5d2098717dfd360b16fce6959b4a222fd241b 100644
--- a/include/staff/syslogs.inc.php
+++ b/include/staff/syslogs.inc.php
@@ -88,13 +88,9 @@ else
  <form action="syslogs.php" method="get">
     <div style="padding-left:2px;">
         <b>Date Span</b>:
-        &nbsp;From&nbsp;<input class="dp" id="sd" size=15 name="startDate" value="<?php echo Format::htmlchars($_REQUEST['startDate']); ?>"
-                onclick="event.cancelBubble=true;calendar(this);" autocomplete=OFF>
-            <a href="#" onclick="event.cancelBubble=true;calendar(getObj('sd')); return false;"><img src='images/cal.png'border=0 alt=""></a>
+        &nbsp;From&nbsp;<input class="dp" id="sd" size=15 name="startDate" value="<?php echo Format::htmlchars($_REQUEST['startDate']); ?>" autocomplete=OFF>
             &nbsp;&nbsp; to &nbsp;&nbsp;
-            <input class="dp" id="ed" size=15 name="endDate" value="<?php echo Format::htmlchars($_REQUEST['endDate']); ?>"
-                onclick="event.cancelBubble=true;calendar(this);" autocomplete=OFF >
-                <a href="#" onclick="event.cancelBubble=true;calendar(getObj('ed')); return false;"><img src='images/cal.png'border=0 alt=""></a>
+            <input class="dp" id="ed" size=15 name="endDate" value="<?php echo Format::htmlchars($_REQUEST['endDate']); ?>" autocomplete=OFF>
             &nbsp;&nbsp;
             &nbsp;Type:
             <select name='type'>
diff --git a/include/staff/ticket-edit.inc.php b/include/staff/ticket-edit.inc.php
index db80cf2f73fc53853905be23eaa6430e7eefd1de..7bbf0921e5ed97a076e0dc5df4aa61dde44e27fb 100644
--- a/include/staff/ticket-edit.inc.php
+++ b/include/staff/ticket-edit.inc.php
@@ -139,18 +139,17 @@ $info=Format::htmlchars(($errors && $_POST)?$_POST:$ticket->getUpdateInfo());
                 Due Date:
             </td>
             <td>
-                <input id="duedate" name="duedate" value="<?php echo Format::htmlchars($info['duedate']); ?>" size="10"
-                    onclick="event.cancelBubble=true;calendar(this);" autocomplete=OFF>
-                <a href="#" onclick="event.cancelBubble=true;calendar(getObj('duedate')); return false;"><img src='images/cal.png'border=0 alt=""></a>
+                <input class="dp" id="duedate" name="duedate" value="<?php echo Format::htmlchars($info['duedate']); ?>" size="12" autocomplete=OFF>
                 &nbsp;&nbsp;
                 <?php
                 $min=$hr=null;
                 if($info['time'])
-                    list($hr,$min)=explode(':',$info['time']);
-                    echo Misc::timeDropdown($hr,$min,'time');
+                    list($hr, $min)=explode(':', $info['time']);
+                    
+                echo Misc::timeDropdown($hr, $min, 'time');
                 ?>
                 &nbsp;<font class="error">&nbsp;<?=$errors['duedate']?>&nbsp;<?php echo $errors['time']; ?></font>
-                <em>Time is based on your time zone (GM <?php echo $thisstaff->getTZoffset(); ?>)</em>
+                <em>Time is based on your time zone (GMT <?php echo $thisstaff->getTZoffset(); ?>)</em>
             </td>
         </tr>
         <tr>
diff --git a/include/staff/ticket-open.inc.php b/include/staff/ticket-open.inc.php
index 4ec32b3423abb2c4fa424552ec4b6730a8418e9a..680fbad151ba038104410a3a778f3371841d4ed1 100644
--- a/include/staff/ticket-open.inc.php
+++ b/include/staff/ticket-open.inc.php
@@ -203,18 +203,17 @@ $info=Format::htmlchars(($errors && $_POST)?$_POST:$info);
                 Due Date:
             </td>
             <td>
-                <input id="duedate" name="duedate" value="<?php echo Format::htmlchars($info['duedate']); ?>" size="10"
-                    onclick="event.cancelBubble=true;calendar(this);" autocomplete=OFF>
-                <a href="#" onclick="event.cancelBubble=true;calendar(getObj('duedate')); return false;"><img src='images/cal.png'border=0 alt=""></a>
+                <input class="dp" id="duedate" name="duedate" value="<?php echo Format::htmlchars($info['duedate']); ?>" size="12" autocomplete=OFF>
                 &nbsp;&nbsp;
                 <?php
                 $min=$hr=null;
                 if($info['time'])
-                    list($hr,$min)=explode(':',$info['time']);
-                    echo Misc::timeDropdown($hr,$min,'time');
+                    list($hr, $min)=explode(':', $info['time']);
+                    
+                echo Misc::timeDropdown($hr, $min, 'time');
                 ?>
                 &nbsp;<font class="error">&nbsp;<?=$errors['duedate']?>&nbsp;<?php echo $errors['time']; ?></font>
-                <em>Time is based on your time zone (GM <?php echo $thisstaff->getTZoffset(); ?>)</em>
+                <em>Time is based on your time zone (GMT <?php echo $thisstaff->getTZoffset(); ?>)</em>
             </td>
         </tr>
         <tr>
diff --git a/include/staff/tickets.inc.php b/include/staff/tickets.inc.php
index 9d6d5c7bcf0005e315f4e6e032943c97a237c01d..bd4801c445cadc40677b3dcdb3bf163b280abfc8 100644
--- a/include/staff/tickets.inc.php
+++ b/include/staff/tickets.inc.php
@@ -533,9 +533,9 @@ $negorder=$order=='DESC'?'ASC':'DESC'; //Negate the sorting..
         </fieldset>
         <fieldset class="date_range">
             <label>Date Range:</label>
-            <input class="dp" type="input" size="20" name="startDate"><i></i>
+            <input class="dp" type="input" size="20" name="startDate">
             <span>TO</span>
-            <input class="dp" type="input" size="20" name="endDate"><i></i>
+            <input class="dp" type="input" size="20" name="endDate">
         </fieldset>
         <p>
             <span class="buttons">
diff --git a/js/jquery-ui-1.8.18.custom.min.js b/js/jquery-ui-1.8.18.custom.min.js
new file mode 100755
index 0000000000000000000000000000000000000000..81486fc8e6f8a32d847668911188813b107536de
--- /dev/null
+++ b/js/jquery-ui-1.8.18.custom.min.js
@@ -0,0 +1,21 @@
+/*!
+ * jQuery UI 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI
+ */(function(a,b){function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;if(!b.href||!g||f.nodeName.toLowerCase()!=="map")return!1;h=a("img[usemap=#"+g+"]")[0];return!!h&&d(h)}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}a.ui=a.ui||{};a.ui.version||(a.extend(a.ui,{version:"1.8.18",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)});return c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){if(c===b)return g["inner"+d].call(this);return this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){if(typeof b!="number")return g["outer"+d].call(this,b);return this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!!d&&!!a.element[0].parentNode)for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(b,c){if(a(b).css("overflow")==="hidden")return!1;var d=c&&c==="left"?"scrollLeft":"scrollTop",e=!1;if(b[d]>0)return!0;b[d]=1,e=b[d]>0,b[d]=0;return e},isOverAxis:function(a,b,c){return a>b&&a<b+c},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}}))})(jQuery);/*
+ * jQuery UI Datepicker 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Datepicker
+ *
+ * Depends:
+ *	jquery.ui.core.js
+ */(function($,undefined){function isArray(a){return a&&($.browser.safari&&typeof a=="object"&&a.length||a.constructor&&a.constructor.toString().match(/\Array\(\)/))}function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}function bindHover(a){var b="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return a.bind("mouseout",function(a){var c=$(a.target).closest(b);!c.length||c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(c){var d=$(c.target).closest(b);!$.datepicker._isDisabledDatepicker(instActive.inline?a.parent()[0]:instActive.input[0])&&!!d.length&&(d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),d.addClass("ui-state-hover"),d.hasClass("ui-datepicker-prev")&&d.addClass("ui-datepicker-prev-hover"),d.hasClass("ui-datepicker-next")&&d.addClass("ui-datepicker-next-hover"))})}function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}$.extend($.ui,{datepicker:{version:"1.8.18"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){extendRemove(this._defaults,a||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(a,b){var c=a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:c,input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:b?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(a,b){var c=$(a);b.append=$([]),b.trigger=$([]);c.hasClass(this.markerClassName)||(this._attachments(c,b),c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),this._autoSize(b),$.data(a,PROP_NAME,b),b.settings.disabled&&this._disableDatepicker(a))},_attachments:function(a,b){var c=this._get(b,"appendText"),d=this._get(b,"isRTL");b.append&&b.append.remove(),c&&(b.append=$('<span class="'+this._appendClass+'">'+c+"</span>"),a[d?"before":"after"](b.append)),a.unbind("focus",this._showDatepicker),b.trigger&&b.trigger.remove();var e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||e=="both"){var f=this._get(b,"buttonText"),g=this._get(b,"buttonImage");b.trigger=$(this._get(b,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:g,alt:f,title:f}):$('<button type="button"></button>').addClass(this._triggerClass).html(g==""?f:$("<img/>").attr({src:g,alt:f,title:f}))),a[d?"before":"after"](b.trigger),b.trigger.click(function(){$.datepicker._datepickerShowing&&$.datepicker._lastInput==a[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=a[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(a[0])):$.datepicker._showDatepicker(a[0]);return!1})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var d=function(a){var b=0,c=0;for(var d=0;d<a.length;d++)a[d].length>b&&(b=a[d].length,c=d);return c};b.setMonth(d(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort"))),b.setDate(d(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=$(a);c.hasClass(this.markerClassName)||(c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),$.data(a,PROP_NAME,b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block"))},_dialogDatepicker:function(a,b,c,d,e){var f=this._dialogInst;if(!f){this.uuid+=1;var g="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+g+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),f=this._dialogInst=this._newInst(this._dialogInput,!1),f.settings={},$.data(this._dialogInput[0],PROP_NAME,f)}extendRemove(f.settings,d||{}),b=b&&b.constructor==Date?this._formatDate(f,b):b,this._dialogInput.val(b),this._pos=e?e.length?e:[e.pageX,e.pageY]:null;if(!this._pos){var h=document.documentElement.clientWidth,i=document.documentElement.clientHeight,j=document.documentElement.scrollLeft||document.body.scrollLeft,k=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[h/2-100+j,i/2-150+k]}this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),f.settings.onSelect=c,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,f);return this},_destroyDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!!b.hasClass(this.markerClassName)){var d=a.nodeName.toLowerCase();$.removeData(a,PROP_NAME),d=="input"?(c.append.remove(),c.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(d=="div"||d=="span")&&b.removeClass(this.markerClassName).empty()}},_enableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!!b.hasClass(this.markerClassName)){var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!1,c.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b})}},_disableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!!b.hasClass(this.markerClassName)){var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!0,c.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b}),this._disabledInputs[this._disabledInputs.length]=a}},_isDisabledDatepicker:function(a){if(!a)return!1;for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return!0;return!1},_getInst:function(a){try{return $.data(a,PROP_NAME)}catch(b){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(a,b,c){var d=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?$.extend({},$.datepicker._defaults):d?b=="all"?$.extend({},d.settings):this._get(d,b):null;var e=b||{};typeof b=="string"&&(e={},e[b]=c);if(d){this._curInst==d&&this._hideDatepicker();var f=this._getDateDatepicker(a,!0),g=this._getMinMaxDate(d,"min"),h=this._getMinMaxDate(d,"max");extendRemove(d.settings,e),g!==null&&e.dateFormat!==undefined&&e.minDate===undefined&&(d.settings.minDate=this._formatDate(d,g)),h!==null&&e.dateFormat!==undefined&&e.maxDate===undefined&&(d.settings.maxDate=this._formatDate(d,h)),this._attachments($(a),d),this._autoSize(d),this._setDate(d,f),this._updateAlternate(d),this._updateDatepicker(d)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){var b=this._getInst(a);b&&this._updateDatepicker(b)},_setDateDatepicker:function(a,b){var c=this._getInst(a);c&&(this._setDate(c,b),this._updateDatepicker(c),this._updateAlternate(c))},_getDateDatepicker:function(a,b){var c=this._getInst(a);c&&!c.inline&&this._setDateFromField(c,b);return c?this._getDate(c):null},_doKeyDown:function(a){var b=$.datepicker._getInst(a.target),c=!0,d=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=!0;if($.datepicker._datepickerShowing)switch(a.keyCode){case 9:$.datepicker._hideDatepicker(),c=!1;break;case 13:var e=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",b.dpDiv);e[0]&&$.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,e[0]);var f=$.datepicker._get(b,"onSelect");if(f){var g=$.datepicker._formatDate(b);f.apply(b.input?b.input[0]:null,[g,b])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 35:(a.ctrlKey||a.metaKey)&&$.datepicker._clearDate(a.target),c=a.ctrlKey||a.metaKey;break;case 36:(a.ctrlKey||a.metaKey)&&$.datepicker._gotoToday(a.target),c=a.ctrlKey||a.metaKey;break;case 37:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?1:-1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 38:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,-7,"D"),c=a.ctrlKey||a.metaKey;break;case 39:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?-1:1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 40:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,7,"D"),c=a.ctrlKey||a.metaKey;break;default:c=!1}else a.keyCode==36&&a.ctrlKey?$.datepicker._showDatepicker(this):c=!1;c&&(a.preventDefault(),a.stopPropagation())},_doKeyPress:function(a){var b=$.datepicker._getInst(a.target);if($.datepicker._get(b,"constrainInput")){var c=$.datepicker._possibleChars($.datepicker._get(b,"dateFormat")),d=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||a.metaKey||d<" "||!c||c.indexOf(d)>-1}},_doKeyUp:function(a){var b=$.datepicker._getInst(a.target);if(b.input.val()!=b.lastVal)try{var c=$.datepicker.parseDate($.datepicker._get(b,"dateFormat"),b.input?b.input.val():null,$.datepicker._getFormatConfig(b));c&&($.datepicker._setDateFromField(b),$.datepicker._updateAlternate(b),$.datepicker._updateDatepicker(b))}catch(a){$.datepicker.log(a)}return!0},_showDatepicker:function(a){a=a.target||a,a.nodeName.toLowerCase()!="input"&&(a=$("input",a.parentNode)[0]);if(!$.datepicker._isDisabledDatepicker(a)&&$.datepicker._lastInput!=a){var b=$.datepicker._getInst(a);$.datepicker._curInst&&$.datepicker._curInst!=b&&($.datepicker._curInst.dpDiv.stop(!0,!0),b&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var c=$.datepicker._get(b,"beforeShow"),d=c?c.apply(a,[a,b]):{};if(d===!1)return;extendRemove(b.settings,d),b.lastVal=null,$.datepicker._lastInput=a,$.datepicker._setDateFromField(b),$.datepicker._inDialog&&(a.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(a),$.datepicker._pos[1]+=a.offsetHeight);var e=!1;$(a).parents().each(function(){e|=$(this).css("position")=="fixed";return!e}),e&&$.browser.opera&&($.datepicker._pos[0]-=document.documentElement.scrollLeft,$.datepicker._pos[1]-=document.documentElement.scrollTop);var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,b.dpDiv.empty(),b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(b),f=$.datepicker._checkOffset(b,f,e),b.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":e?"fixed":"absolute",display:"none",left:f.left+"px",top:f.top+"px"});if(!b.inline){var g=$.datepicker._get(b,"showAnim"),h=$.datepicker._get(b,"duration"),i=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(!!a.length){var c=$.datepicker._getBorders(b.dpDiv);a.css({left:-c[0],top:-c[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex($(a).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&$.effects[g]?b.dpDiv.show(g,$.datepicker._get(b,"showOptions"),h,i):b.dpDiv[g||"show"](g?h:null,i),(!g||!h)&&i(),b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus(),$.datepicker._curInst=b}}},_updateDatepicker:function(a){var b=this;b.maxRows=4;var c=$.datepicker._getBorders(a.dpDiv);instActive=a,a.dpDiv.empty().append(this._generateHTML(a));var d=a.dpDiv.find("iframe.ui-datepicker-cover");!d.length||d.css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}),a.dpDiv.find("."+this._dayOverClass+" a").mouseover();var e=this._getNumberOfMonths(a),f=e[1],g=17;a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),f>1&&a.dpDiv.addClass("ui-datepicker-multi-"+f).css("width",g*f+"em"),a.dpDiv[(e[0]!=1||e[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),a==$.datepicker._curInst&&$.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var h=a.yearshtml;setTimeout(function(){h===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml),h=a.yearshtml=null},0)}},_getBorders:function(a){var b=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var d=a.dpDiv.outerWidth(),e=a.dpDiv.outerHeight(),f=a.input?a.input.outerWidth():0,g=a.input?a.input.outerHeight():0,h=document.documentElement.clientWidth+$(document).scrollLeft(),i=document.documentElement.clientHeight+$(document).scrollTop();b.left-=this._get(a,"isRTL")?d-f:0,b.left-=c&&b.left==a.input.offset().left?$(document).scrollLeft():0,b.top-=c&&b.top==a.input.offset().top+g?$(document).scrollTop():0,b.left-=Math.min(b.left,b.left+d>h&&h>d?Math.abs(b.left+d-h):0),b.top-=Math.min(b.top,b.top+e>i&&i>e?Math.abs(e+g):0);return b},_findPos:function(a){var b=this._getInst(a),c=this._get(b,"isRTL");while(a&&(a.type=="hidden"||a.nodeType!=1||$.expr.filters.hidden(a)))a=a[c?"previousSibling":"nextSibling"];var d=$(a).offset();return[d.left,d.top]},_hideDatepicker:function(a){var b=this._curInst;if(!(!b||a&&b!=$.data(a,PROP_NAME))&&this._datepickerShowing){var c=this._get(b,"showAnim"),d=this._get(b,"duration"),e=this,f=function(){$.datepicker._tidyDialog(b),e._curInst=null};$.effects&&$.effects[c]?b.dpDiv.hide(c,$.datepicker._get(b,"showOptions"),d,f):b.dpDiv[c=="slideDown"?"slideUp":c=="fadeIn"?"fadeOut":"hide"](c?d:null,f),c||f(),this._datepickerShowing=!1;var g=this._get(b,"onClose");g&&g.apply(b.input?b.input[0]:null,[b.input?b.input.val():"",b]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(!!$.datepicker._curInst){var b=$(a.target),c=$.datepicker._getInst(b[0]);(b[0].id!=$.datepicker._mainDivId&&b.parents("#"+$.datepicker._mainDivId).length==0&&!b.hasClass($.datepicker.markerClassName)&&!b.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||b.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=c)&&$.datepicker._hideDatepicker()}},_adjustDate:function(a,b,c){var d=$(a),e=this._getInst(d[0]);this._isDisabledDatepicker(d[0])||(this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c),this._updateDatepicker(e))},_gotoToday:function(a){var b=$(a),c=this._getInst(b[0]);if(this._get(c,"gotoCurrent")&&c.currentDay)c.selectedDay=c.currentDay,c.drawMonth=c.selectedMonth=c.currentMonth,c.drawYear=c.selectedYear=c.currentYear;else{var d=new Date;c.selectedDay=d.getDate(),c.drawMonth=c.selectedMonth=d.getMonth(),c.drawYear=c.selectedYear=d.getFullYear()}this._notifyChange(c),this._adjustDate(b)},_selectMonthYear:function(a,b,c){var d=$(a),e=this._getInst(d[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(d)},_selectDay:function(a,b,c,d){var e=$(a);if(!$(d).hasClass(this._unselectableClass)&&!this._isDisabledDatepicker(e[0])){var f=this._getInst(e[0]);f.selectedDay=f.currentDay=$("a",d).html(),f.selectedMonth=f.currentMonth=b,f.selectedYear=f.currentYear=c,this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))}},_clearDate:function(a){var b=$(a),c=this._getInst(b[0]);this._selectDate(b,"")},_selectDate:function(a,b){var c=$(a),d=this._getInst(c[0]);b=b!=null?b:this._formatDate(d),d.input&&d.input.val(b),this._updateAlternate(d);var e=this._get(d,"onSelect");e?e.apply(d.input?d.input[0]:null,[b,d]):d.input&&d.input.trigger("change"),d.inline?this._updateDatepicker(d):(this._hideDatepicker(),this._lastInput=d.input[0],typeof d.input[0]!="object"&&d.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),d=this._getDate(a),e=this.formatDate(c,d,this._getFormatConfig(a));$(b).each(function(){$(this).val(e)})}},noWeekends:function(a){var b=a.getDay();return[b>0&&b<6,""]},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();b.setMonth(0),b.setDate(1);return Math.floor(Math.round((c-b)/864e5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;var d=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,g=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,h=(c?c.monthNames:null)||this._defaults.monthNames,i=-1,j=-1,k=-1,l=-1,m=!1,n=function(b){var c=s+1<a.length&&a.charAt(s+1)==b;c&&s++;return c},o=function(a){var c=n(a),d=a=="@"?14:a=="!"?20:a=="y"&&c?4:a=="o"?3:2,e=new RegExp("^\\d{1,"+d+"}"),f=b.substring(r).match(e);if(!f)throw"Missing number at position "+r;r+=f[0].length;return parseInt(f[0],10)},p=function(a,c,d){var e=$.map(n(a)?d:c,function(a,b){return[[b,a]]}).sort(function(a,b){return-(a[1].length-b[1].length)}),f=-1;$.each(e,function(a,c){var d=c[1];if(b.substr(r,d.length).toLowerCase()==d.toLowerCase()){f=c[0],r+=d.length;return!1}});if(f!=-1)return f+1;throw"Unknown name at position "+r},q=function(){if(b.charAt(r)!=a.charAt(s))throw"Unexpected literal at position "+r;r++},r=0;for(var s=0;s<a.length;s++)if(m)a.charAt(s)=="'"&&!n("'")?m=!1:q();else switch(a.charAt(s)){case"d":k=o("d");break;case"D":p("D",e,f);break;case"o":l=o("o");break;case"m":j=o("m");break;case"M":j=p("M",g,h);break;case"y":i=o("y");break;case"@":var t=new Date(o("@"));i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"!":var t=new Date((o("!")-this._ticksTo1970)/1e4);i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"'":n("'")?q():m=!0;break;default:q()}if(r<b.length)throw"Extra/unparsed characters found in date: "+b.substring(r);i==-1?i=(new Date).getFullYear():i<100&&(i+=(new Date).getFullYear()-(new Date).getFullYear()%100+(i<=d?0:-100));if(l>-1){j=1,k=l;for(;;){var u=this._getDaysInMonth(i,j-1);if(k<=u)break;j++,k-=u}}var t=this._daylightSavingAdjust(new Date(i,j-1,k));if(t.getFullYear()!=i||t.getMonth()+1!=j||t.getDate()!=k)throw"Invalid date";return t},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(a,b,c){if(!b)return"";var d=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,e=(c?c.dayNames:null)||this._defaults.dayNames,f=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,h=function(b){var c=m+1<a.length&&a.charAt(m+1)==b;c&&m++;return c},i=function(a,b,c){var d=""+b;if(h(a))while(d.length<c)d="0"+d;return d},j=function(a,b,c,d){return h(a)?d[b]:c[b]},k="",l=!1;if(b)for(var m=0;m<a.length;m++)if(l)a.charAt(m)=="'"&&!h("'")?l=!1:k+=a.charAt(m);else switch(a.charAt(m)){case"d":k+=i("d",b.getDate(),2);break;case"D":k+=j("D",b.getDay(),d,e);break;case"o":k+=i("o",Math.round(((new Date(b.getFullYear(),b.getMonth(),b.getDate())).getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":k+=i("m",b.getMonth()+1,2);break;case"M":k+=j("M",b.getMonth(),f,g);break;case"y":k+=h("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case"@":k+=b.getTime();break;case"!":k+=b.getTime()*1e4+this._ticksTo1970;break;case"'":h("'")?k+="'":l=!0;break;default:k+=a.charAt(m)}return k},_possibleChars:function(a){var b="",c=!1,d=function(b){var c=e+1<a.length&&a.charAt(e+1)==b;c&&e++;return c};for(var e=0;e<a.length;e++)if(c)a.charAt(e)=="'"&&!d("'")?c=!1:b+=a.charAt(e);else switch(a.charAt(e)){case"d":case"m":case"y":case"@":b+="0123456789";break;case"D":case"M":return null;case"'":d("'")?b+="'":c=!0;break;default:b+=a.charAt(e)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()!=a.lastVal){var c=this._get(a,"dateFormat"),d=a.lastVal=a.input?a.input.val():null,e,f;e=f=this._getDefaultDate(a);var g=this._getFormatConfig(a);try{e=this.parseDate(c,d,g)||f}catch(h){this.log(h),d=b?"":d}a.selectedDay=e.getDate(),a.drawMonth=a.selectedMonth=e.getMonth(),a.drawYear=a.selectedYear=e.getFullYear(),a.currentDay=d?e.getDate():0,a.currentMonth=d?e.getMonth():0,a.currentYear=d?e.getFullYear():0,this._adjustInstDate(a)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},_determineDate:function(a,b,c){var d=function(a){var b=new Date;b.setDate(b.getDate()+a);return b},e=function(b){try{return $.datepicker.parseDate($.datepicker._get(a,"dateFormat"),b,$.datepicker._getFormatConfig(a))}catch(c){}var d=(b.toLowerCase().match(/^c/)?$.datepicker._getDate(a):null)||new Date,e=d.getFullYear(),f=d.getMonth(),g=d.getDate(),h=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,i=h.exec(b);while(i){switch(i[2]||"d"){case"d":case"D":g+=parseInt(i[1],10);break;case"w":case"W":g+=parseInt(i[1],10)*7;break;case"m":case"M":f+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f));break;case"y":case"Y":e+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f))}i=h.exec(b)}return new Date(e,f,g)},f=b==null||b===""?c:typeof b=="string"?e(b):typeof b=="number"?isNaN(b)?c:d(b):new Date(b.getTime());f=f&&f.toString()=="Invalid Date"?c:f,f&&(f.setHours(0),f.setMinutes(0),f.setSeconds(0),f.setMilliseconds(0));return this._daylightSavingAdjust(f)},_daylightSavingAdjust:function(a){if(!a)return null;a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,b,c){var d=!b,e=a.selectedMonth,f=a.selectedYear,g=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=g.getDate(),a.drawMonth=a.selectedMonth=a.currentMonth=g.getMonth(),a.drawYear=a.selectedYear=a.currentYear=g.getFullYear(),(e!=a.selectedMonth||f!=a.selectedYear)&&!c&&this._notifyChange(a),this._adjustInstDate(a),a.input&&a.input.val(d?"":this._formatDate(a))},_getDate:function(a){var b=!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return b},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),d=this._get(a,"showButtonPanel"),e=this._get(a,"hideIfNoPrevNext"),f=this._get(a,"navigationAsDateFormat"),g=this._getNumberOfMonths(a),h=this._get(a,"showCurrentAtPos"),i=this._get(a,"stepMonths"),j=g[0]!=1||g[1]!=1,k=this._daylightSavingAdjust(a.currentDay?new Date(a.currentYear,a.currentMonth,a.currentDay):new Date(9999,9,9)),l=this._getMinMaxDate(a,"min"),m=this._getMinMaxDate(a,"max"),n=a.drawMonth-h,o=a.drawYear;n<0&&(n+=12,o--);if(m){var p=this._daylightSavingAdjust(new Date(m.getFullYear(),m.getMonth()-g[0]*g[1]+1,m.getDate()));p=l&&p<l?l:p;while(this._daylightSavingAdjust(new Date(o,n,1))>p)n--,n<0&&(n=11,o--)}a.drawMonth=n,a.drawYear=o;var q=this._get(a,"prevText");q=f?this.formatDate(q,this._daylightSavingAdjust(new Date(o,n-i,1)),this._getFormatConfig(a)):q;var r=this._canAdjustMonth(a,-1,o,n)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', -"+i+", 'M');\""+' title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>":e?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>",s=this._get(a,"nextText");s=f?this.formatDate(s,this._daylightSavingAdjust(new Date(o,n+i,1)),this._getFormatConfig(a)):s;var t=this._canAdjustMonth(a,1,o,n)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', +"+i+", 'M');\""+' title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>":e?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>",u=this._get(a,"currentText"),v=this._get(a,"gotoCurrent")&&a.currentDay?k:b;u=f?this.formatDate(u,v,this._getFormatConfig(a)):u;var w=a.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+dpuuid+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>",x=d?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?w:"")+(this._isInRange(a,v)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._gotoToday('#"+a.id+"');\""+">"+u+"</button>":"")+(c?"":w)+"</div>":"",y=parseInt(this._get(a,"firstDay"),10);y=isNaN(y)?0:y;var z=this._get(a,"showWeek"),A=this._get(a,"dayNames"),B=this._get(a,"dayNamesShort"),C=this._get(a,"dayNamesMin"),D=this._get(a,"monthNames"),E=this._get(a,"monthNamesShort"),F=this._get(a,"beforeShowDay"),G=this._get(a,"showOtherMonths"),H=this._get(a,"selectOtherMonths"),I=this._get(a,"calculateWeek")||this.iso8601Week,J=this._getDefaultDate(a),K="";for(var L=0;L<g[0];L++){var M="";this.maxRows=4;for(var N=0;N<g[1];N++){var O=this._daylightSavingAdjust(new Date(o,n,a.selectedDay)),P=" ui-corner-all",Q="";if(j){Q+='<div class="ui-datepicker-group';if(g[1]>1)switch(N){case 0:Q+=" ui-datepicker-group-first",P=" ui-corner-"+(c?"right":"left");break;case g[1]-1:Q+=" ui-datepicker-group-last",P=" ui-corner-"+(c?"left":"right");break;default:Q+=" ui-datepicker-group-middle",P=""}Q+='">'}Q+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+P+'">'+(/all|left/.test(P)&&L==0?c?t:r:"")+(/all|right/.test(P)&&L==0?c?r:t:"")+this._generateMonthYearHeader(a,n,o,l,m,L>0||N>0,D,E)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var R=z?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(var S=0;S<7;S++){var T=(S+y)%7;R+="<th"+((S+y+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+A[T]+'">'+C[T]+"</span></th>"}Q+=R+"</tr></thead><tbody>";var U=this._getDaysInMonth(o,n);o==a.selectedYear&&n==a.selectedMonth&&(a.selectedDay=Math.min(a.selectedDay,U));var V=(this._getFirstDayOfMonth(o,n)-y+7)%7,W=Math.ceil((V+U)/7),X=j?this.maxRows>W?this.maxRows:W:W;this.maxRows=X;var Y=this._daylightSavingAdjust(new Date(o,n,1-V));for(var Z=0;Z<X;Z++){Q+="<tr>";var _=z?'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(Y)+"</td>":"";for(var S=0;S<7;S++){var ba=F?F.apply(a.input?a.input[0]:null,[Y]):[!0,""],bb=Y.getMonth()!=n,bc=bb&&!H||!ba[0]||l&&Y<l||m&&Y>m;_+='<td class="'+((S+y+6)%7>=5?" ui-datepicker-week-end":"")+(bb?" ui-datepicker-other-month":"")+(Y.getTime()==O.getTime()&&n==a.selectedMonth&&a._keyEvent||J.getTime()==Y.getTime()&&J.getTime()==O.getTime()?" "+this._dayOverClass:"")+(bc?" "+this._unselectableClass+" ui-state-disabled":"")+(bb&&!G?"":" "+ba[1]+(Y.getTime()==k.getTime()?" "+this._currentClass:"")+(Y.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!bb||G)&&ba[2]?' title="'+ba[2]+'"':"")+(bc?"":' onclick="DP_jQuery_'+dpuuid+".datepicker._selectDay('#"+a.id+"',"+Y.getMonth()+","+Y.getFullYear()+', this);return false;"')+">"+(bb&&!G?"&#xa0;":bc?'<span class="ui-state-default">'+Y.getDate()+"</span>":'<a class="ui-state-default'+(Y.getTime()==b.getTime()?" ui-state-highlight":"")+(Y.getTime()==k.getTime()?" ui-state-active":"")+(bb?" ui-priority-secondary":"")+'" href="#">'+Y.getDate()+"</a>")+"</td>",Y.setDate(Y.getDate()+1),Y=this._daylightSavingAdjust(Y)}Q+=_+"</tr>"}n++,n>11&&(n=0,o++),Q+="</tbody></table>"+(j?"</div>"+(g[0]>0&&N==g[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),M+=Q}K+=M}K+=x+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),
+a._keyEvent=!1;return K},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h){var i=this._get(a,"changeMonth"),j=this._get(a,"changeYear"),k=this._get(a,"showMonthAfterYear"),l='<div class="ui-datepicker-title">',m="";if(f||!i)m+='<span class="ui-datepicker-month">'+g[b]+"</span>";else{var n=d&&d.getFullYear()==c,o=e&&e.getFullYear()==c;m+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" "+">";for(var p=0;p<12;p++)(!n||p>=d.getMonth())&&(!o||p<=e.getMonth())&&(m+='<option value="'+p+'"'+(p==b?' selected="selected"':"")+">"+h[p]+"</option>");m+="</select>"}k||(l+=m+(f||!i||!j?"&#xa0;":""));if(!a.yearshtml){a.yearshtml="";if(f||!j)l+='<span class="ui-datepicker-year">'+c+"</span>";else{var q=this._get(a,"yearRange").split(":"),r=(new Date).getFullYear(),s=function(a){var b=a.match(/c[+-].*/)?c+parseInt(a.substring(1),10):a.match(/[+-].*/)?r+parseInt(a,10):parseInt(a,10);return isNaN(b)?r:b},t=s(q[0]),u=Math.max(t,s(q[1]||""));t=d?Math.max(t,d.getFullYear()):t,u=e?Math.min(u,e.getFullYear()):u,a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" "+">";for(;t<=u;t++)a.yearshtml+='<option value="'+t+'"'+(t==c?' selected="selected"':"")+">"+t+"</option>";a.yearshtml+="</select>",l+=a.yearshtml,a.yearshtml=null}}l+=this._get(a,"yearSuffix"),k&&(l+=(f||!i||!j?"&#xa0;":"")+m),l+="</div>";return l},_adjustInstDate:function(a,b,c){var d=a.drawYear+(c=="Y"?b:0),e=a.drawMonth+(c=="M"?b:0),f=Math.min(a.selectedDay,this._getDaysInMonth(d,e))+(c=="D"?b:0),g=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(d,e,f)));a.selectedDay=g.getDate(),a.drawMonth=a.selectedMonth=g.getMonth(),a.drawYear=a.selectedYear=g.getFullYear(),(c=="M"||c=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max"),e=c&&b<c?c:b;e=d&&e>d?d:e;return e},_notifyChange:function(a){var b=this._get(a,"onChangeMonthYear");b&&b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){var b=this._get(a,"numberOfMonths");return b==null?[1,1]:typeof b=="number"?[1,b]:b},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a),f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));b<0&&f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth()));return this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!d||b.getTime()<=d.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10);return{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,d){b||(a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear);var e=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(d,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),e,this._getFormatConfig(a))}}),$.fn.datepicker=function(a){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv),$.datepicker.initialized=!0);var b=Array.prototype.slice.call(arguments,1);if(typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget"))return $.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b));if(a=="option"&&arguments.length==2&&typeof arguments[1]=="string")return $.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b));return this.each(function(){typeof a=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this].concat(b)):$.datepicker._attachDatepicker(this,a)})},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.8.18",window["DP_jQuery_"+dpuuid]=$})(jQuery);
\ No newline at end of file
diff --git a/login.php b/login.php
index 48dc9ec4aea9a5ab7c427cacc30b17c8005944b5..823c48a030d494f2b6ae4f06bbbcf35c8de8918d 100644
--- a/login.php
+++ b/login.php
@@ -53,10 +53,10 @@ if($_POST && (!empty($_POST['lemail']) && !empty($_POST['lticket']))):
             $_SESSION['_client']['key']      =$ticket->getExtId(); //Ticket ID --acts as password when used with email. See above.
             $_SESSION['_client']['token']    =$user->getSessionToken();
             $_SESSION['TZ_OFFSET']=$cfg->getTZoffset();
-            $_SESSION['daylight']=$cfg->observeDaylightSaving();
+            $_SESSION['TZ_DST']=$cfg->observeDaylightSaving();
             //Log login info...
             $msg=sprintf("%s/%s logged in [%s]",$ticket->getEmail(),$ticket->getExtId(),$_SERVER['REMOTE_ADDR']);
-            Sys::log(LOG_DEBUG,'User login',$msg);
+            $ost->logDebug('User login', $msg);
             //Redirect tickets.php
             session_write_close();
             session_regenerate_id();
@@ -75,11 +75,11 @@ if($_POST && (!empty($_POST['lemail']) && !empty($_POST['lticket']))):
                 'Email: '.$_POST['lemail']."\n".'Ticket#: '.$_POST['lticket']."\n".
                 'IP: '.$_SERVER['REMOTE_ADDR']."\n".'Time:'.date('M j, Y, g:i a T')."\n\n".
                 'Attempts #'.$_SESSION['_client']['strikes'];
-        Sys::log(LOG_ALERT,'Excessive login attempts (client)',$alert,($cfg->alertONLoginError()));
+        $ost->logError('Excessive login attempts (client)', $alert, ($cfg->alertONLoginError()));
     }elseif($_SESSION['_client']['strikes']%2==0){ //Log every other failed login attempt as a warning.
         $alert='Email: '.$_POST['lemail']."\n".'Ticket #: '.$_POST['lticket']."\n".'IP: '.$_SERVER['REMOTE_ADDR'].
                "\n".'TIME: '.date('M j, Y, g:i a T')."\n\n".'Attempts #'.$_SESSION['_client']['strikes'];
-        Sys::log(LOG_WARNING,'Failed login attempt (client)',$alert);
+        $ost->logWarning('Failed login attempt (client)', $alert);
     }
 endif;
 
diff --git a/main.inc.php b/main.inc.php
index 0bfcf903a91866cd9c046f3d90020e3539cd935a..57769d32c5fc1d55a6b6d4857aa48cc5da8587fb 100644
--- a/main.inc.php
+++ b/main.inc.php
@@ -65,7 +65,7 @@
         $configfile=INCLUDE_DIR.'settings.php';
     elseif(file_exists(INCLUDE_DIR.'ost-config.php')) //NEW config file v 1.6 stable ++
         $configfile=INCLUDE_DIR.'ost-config.php';
-    elseif(file_exists(ROOT_DIR.'include/'))
+    elseif(file_exists(ROOT_DIR.'setup/'))
         header('Location: '.ROOT_PATH.'setup/');
 
     if(!$configfile || !file_exists($configfile)) die('<b>Error loading settings. Contact admin.</b>');
@@ -86,10 +86,10 @@
    
 
     #include required files
+    require(INCLUDE_DIR.'class.osticket.php');
     require(INCLUDE_DIR.'class.ostsession.php');
     require(INCLUDE_DIR.'class.usersession.php');
     require(INCLUDE_DIR.'class.pagenate.php'); //Pagenate helper!
-    require(INCLUDE_DIR.'class.sys.php'); //system loader & config & logger.    
     require(INCLUDE_DIR.'class.log.php');
     require(INCLUDE_DIR.'class.mcrypt.php');
     require(INCLUDE_DIR.'class.misc.php');
@@ -158,26 +158,25 @@
     $ferror=null;
     if (!db_connect(DBHOST,DBUSER,DBPASS) || !db_select_database(DBNAME)) {
         $ferror='Unable to connect to the database';
-    }elseif(!($cfg=Sys::getConfig())){
+    } elseif(!($ost=osTicket::start(1)) || !($cfg = $ost->getConfig())) {
         $ferror='Unable to load config info from DB. Get tech support.';
     }
-    if($ferror){ //Fatal error
-        Sys::alertAdmin('osTicket Fatal Error',$ferror); //try alerting admin.
-        die("<b>Fatal Error:</b> Contact system administrator."); //Generic error.
+
+    if($ferror) { //Fatal error
+        //try alerting admin using email in config file
+        $msg=$ferror."\n\n".THISPAGE;
+        Email::sendmail(ADMIN_EMAIL, 'osTicket Fatal Error', $msg, sprintf('"osTicket Alerts"<%s>', ADMIN_EMAIL));
+        //Display generic error to the user
+        die("<b>Fatal Error:</b> Contact system administrator.");
         exit;
     }
+    
     //Init
-    $cfg->init();
+    $session = $ost->getSession();
 
     //System defaults we might want to make global//
     #pagenation default - user can overwrite it!
-    define('DEFAULT_PAGE_LIMIT',$cfg->getPageSize()?$cfg->getPageSize():25);
-
-    //Start session handler!
-    $session=osTicketSession::start(SESSION_TTL); // start_session 
-    //Set default timezone...staff will overwrite it.
-    $_SESSION['TZ_OFFSET']=$cfg->getTZoffset();
-    $_SESSION['daylight']=$cfg->observeDaylightSaving();
+    define('DEFAULT_PAGE_LIMIT', $cfg->getPageSize()?$cfg->getPageSize():25);
 
     #Cleanup magic quotes crap.
     if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
diff --git a/scp/admin.inc.php b/scp/admin.inc.php
index 5f6f5e7633422251ca7bbf8960f69461a8afbc35..89e234e2f13e14204701348fa2222ae195930ea2 100644
--- a/scp/admin.inc.php
+++ b/scp/admin.inc.php
@@ -15,16 +15,16 @@
 **********************************************************************/
 require('staff.inc.php');
 //Make sure config is loaded and the staff is set and of admin type
-if(!$cfg or !$thisstaff or !$thisstaff->isAdmin()){
+if(!$ost or !$thisstaff or !$thisstaff->isAdmin()){
     header('Location: index.php');
     require('index.php'); // just in case!
     exit;
 }
 
 //Some security related warnings - bitch until fixed!!! :)
-if($cfg->isUpgradePending()) {
+if($ost->isUpgradePending()) {
     $errors['err']=$sysnotice='System upgrade is pending <a href="../setup/upgrade.php">Upgrade Now</a>';
-} elseif(!$cfg->isHelpDeskOffline()) {
+} else {
     
     if(file_exists('../setup/')) {
         $sysnotice='Please take a minute to delete <strong>setup/install</strong> directory (../setup/) for security reasons.';
diff --git a/scp/autocron.php b/scp/autocron.php
index 589ea416e85d0ef5524d1bd8d9f28ce590bce0ef..366351c9defedffd2bccd478b1d3c8bd2e349ba4 100644
--- a/scp/autocron.php
+++ b/scp/autocron.php
@@ -35,8 +35,9 @@ require_once(INCLUDE_DIR.'class.cron.php');
 Cron::TicketMonitor(); //Age tickets: We're going to age tickets ever regardless of cron settings. 
 if($cfg && $cfg->enableAutoCron()){ //ONLY fetch tickets if autocron is enabled!
     Cron::MailFetcher();  //Fetch mail.
-    Sys::log(LOG_DEBUG,'Autocron','cron job executed ['.$thisstaff->getUserName().']');
-}    
+    $ost->logDebug('Autocron', 'Cron job executed ['.$thisstaff->getUserName().']');
+} 
+
 $_SESSION['lastcroncall']=time();
 endif;
 $output = ob_get_contents();
diff --git a/scp/css/scp.css b/scp/css/scp.css
index adde43fafd105f9a5da9b778bb94f7103aebe2ed..aa6ca4782492783d221fef0c6b18fe412f3cbcd5 100644
--- a/scp/css/scp.css
+++ b/scp/css/scp.css
@@ -1290,3 +1290,16 @@ time {
     background:#ffd8d8;
     border:1px solid #a00;
 }
+
+/* Custom css for datepicker */
+.ui-datepicker-trigger {
+    display:inline-block;
+    border:0;
+    padding:0;
+    margin-left:2px;
+    position:relative;
+    top:5px;
+    width:16px;
+    height:16px;
+    background:inherit;
+}
diff --git a/scp/js/calendar.js b/scp/js/calendar.js
deleted file mode 100644
index 3a9c87601147e6e97b6990cdf5f23be16ee1e8c1..0000000000000000000000000000000000000000
--- a/scp/js/calendar.js
+++ /dev/null
@@ -1,254 +0,0 @@
-/* 
-   Tiny DHTML Calendar
-
-   Stolen somewhere online....add credit.
-   
- */
-
-function getObj(objID)
-{
-    if (document.getElementById) {return document.getElementById(objID);}
-    else if (document.all) {return document.all[objID];}
-    else if (document.layers) {return document.layers[objID];}
-}
-
-function checkClick(e) {
-	e?evt=e:evt=event;
-	CSE=evt.target?evt.target:evt.srcElement;
-	if (getObj('fc'))
-		if (!isChild(CSE,getObj('fc')))
-			getObj('fc').style.display='none';
-}
-
-function isChild(s,d) {
-	while(s) {
-		if (s==d) 
-			return true;
-		s=s.parentNode;
-	}
-	return false;
-}
-
-function Left(obj)
-{
-	var curleft = 0;
-	if (obj.offsetParent)
-	{
-		while (obj.offsetParent)
-		{
-			curleft += obj.offsetLeft
-			obj = obj.offsetParent;
-		}
-	}
-	else if (obj.x)
-		curleft += obj.x;
-
-    
-	return curleft;
-}
-
-function Top(obj)
-{
-	var curtop = 0;
-	if (obj.offsetParent)
-	{
-		while (obj.offsetParent)
-		{
-			curtop += obj.offsetTop
-			obj = obj.offsetParent;
-		}
-	}
-	else if (obj.y)
-		curtop += obj.y;
-	return curtop;
-}
-	
-document.write('<table id="fc" style="position:absolute;border-collapse:collapse;background:#FFFFFF;border:1px solid #ABABAB;display:none" cellpadding=2>');
-document.write('<tr><td style="cursor:pointer" onclick="csubm()"><img src="images/arrowleftmonth.gif"></td><td colspan=5 id="mns" align="center" style="font:bold 13px Arial;text-align:center"></td><td align="right" style="cursor:pointer" onclick="caddm()"><img src="images/arrowrightmonth.gif"></td></tr>');
-document.write('<tr><td align=center style="background:#ABABAB;font:12px Arial">S</td><td align=center style="background:#ABABAB;font:12px Arial">M</td><td align=center style="background:#ABABAB;font:12px Arial">T</td><td align=center style="background:#ABABAB;font:12px Arial">W</td><td align=center style="background:#ABABAB;font:12px Arial">T</td><td align=center style="background:#ABABAB;font:12px Arial">F</td><td align=center style="background:#ABABAB;font:12px Arial">S</td></tr>');
-for(var kk=1;kk<=6;kk++) {
-	document.write('<tr>');
-	for(var tt=1;tt<=7;tt++) {
-		num=7 * (kk-1) - (-tt);
-		document.write('<td id="v' + num + '" style="width:18px;height:18px">&nbsp;</td>');
-	}
-	document.write('</tr>');
-}
-document.write('</table>');
-
-document.all?document.attachEvent('onclick',checkClick):document.addEventListener('click',checkClick,false);
-
-
-// Calendar script
-var now = new Date;
-var sccm=now.getMonth();
-var sccy=now.getFullYear();
-var ccm=now.getMonth();
-var ccy=now.getFullYear();
-
-var updobj;
-
-function calendar(ielem) {
-    
-    if(ielem) {
-        ielem.select();
-        lcs(ielem);
-    }
-}
-
-
-function lcs(ielem) {
-	updobj=ielem;
-	getObj('fc').style.left=Left(ielem)+'px';
-	getObj('fc').style.top=Top(ielem)+ielem.offsetHeight+'px';
-	getObj('fc').style.display='';
-
-	// First check date is valid
-	curdt=ielem.value;
-	curdtarr=curdt.split('/');
-	isdt=true;
-	for(var k=0;k<curdtarr.length;k++) {
-		if (isNaN(curdtarr[k]))
-			isdt=false;
-	}
-	if (isdt&(curdtarr.length==3)) {
-		ccm=curdtarr[0]-1;
-		ccy=curdtarr[2];
-		prepcalendar(curdtarr[1],curdtarr[0]-1,curdtarr[2]);
-	}
-	
-}
-
-function evtTgt(e)
-{
-	var el;
-	if(e.target)el=e.target;
-	else if(e.srcElement)el=e.srcElement;
-	if(el.nodeType==3)el=el.parentNode; // defeat Safari bug
-	return el;
-}
-function EvtObj(e){if(!e)e=window.event;return e;}
-function cs_over(e) {
-	evtTgt(EvtObj(e)).style.background='#FFCC66';
-}
-function cs_out(e) {
-	evtTgt(EvtObj(e)).style.background='#C4D3EA';
-}
-function cs_click(e) {
-	updobj.value=calvalarr[evtTgt(EvtObj(e)).id.substring(1,evtTgt(EvtObj(e)).id.length)];
-	getObj('fc').style.display='none';
-	
-}
-
-var mn=new Array('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');
-var mnn=new Array('31','28','31','30','31','30','31','31','30','31','30','31');
-var mnl=new Array('31','29','31','30','31','30','31','31','30','31','30','31');
-var calvalarr=new Array(42);
-
-function f_cps(obj) {
-	obj.style.background='#C4D3EA';
-	obj.style.font='10px Arial';
-	obj.style.color='#333333';
-	obj.style.textAlign='center';
-	obj.style.textDecoration='none';
-	obj.style.border='1px solid #6487AE';
-	obj.style.cursor='pointer';
-}
-
-function f_cpps(obj) {
-	obj.style.background='#C4D3EA';
-	obj.style.font='10px Arial';
-	obj.style.color='#ABABAB';
-	obj.style.textAlign='center';
-	obj.style.textDecoration='line-through';
-	obj.style.border='1px solid #6487AE';
-	obj.style.cursor='default';
-}
-
-function f_hds(obj) {
-	obj.style.background='#FFF799';
-	obj.style.font='bold 10px Arial';
-	obj.style.color='#333333';
-	obj.style.textAlign='center';
-	obj.style.border='1px solid #6487AE';
-	obj.style.cursor='pointer';
-}
-
-// day selected
-function prepcalendar(hd,cm,cy) {
-	now=new Date();
-	sd=now.getDate();
-	td=new Date();
-	td.setDate(1);
-	td.setFullYear(cy);
-	td.setMonth(cm);
-	cd=td.getDay();
-	getObj('mns').innerHTML=mn[cm]+ ' ' + cy;
-	marr=((cy%4)==0)?mnl:mnn;
-	for(var d=1;d<=42;d++) {
-		f_cps(getObj('v'+parseInt(d)));
-		if ((d >= (cd -(-1))) && (d<=cd-(-marr[cm]))) {
-			dip=((d-cd < sd)&&(cm==sccm)&&(cy==sccy));
-			htd=((hd!='')&&(d-cd==hd));
-			if (0 && dip)
-				f_cpps(getObj('v'+parseInt(d)));
-			else if (htd)
-				f_hds(getObj('v'+parseInt(d)));
-			else
-				f_cps(getObj('v'+parseInt(d)));
-
-			getObj('v'+parseInt(d)).onmouseover=cs_over;
-			getObj('v'+parseInt(d)).onmouseout=cs_out;
-			getObj('v'+parseInt(d)).onclick=cs_click;
-			
-			getObj('v'+parseInt(d)).innerHTML=d-cd;	
-			calvalarr[d]=''+(cm-(-1))+'/'+(d-cd)+'/'+cy;
-		}
-		else {
-			getObj('v'+d).innerHTML='&nbsp;';
-			getObj('v'+parseInt(d)).onmouseover=null;
-			getObj('v'+parseInt(d)).onmouseout=null;
-			getObj('v'+parseInt(d)).style.cursor='default';
-			}
-	}
-}
-
-prepcalendar('',ccm,ccy);
-//getObj('fc'+cc).style.visibility='hidden';
-
-function caddm() {
-	marr=((ccy%4)==0)?mnl:mnn;
-	
-	ccm+=1;
-	if (ccm>=12) {
-		ccm=0;
-		ccy++;
-	}
-	cdayf();
-	prepcalendar('',ccm,ccy);
-}
-
-function csubm() {
-	marr=((ccy%4)==0)?mnl:mnn;
-	
-	ccm-=1;
-	if (ccm<0) {
-		ccm=11;
-		ccy--;
-	}
-	cdayf();
-	prepcalendar('',ccm,ccy);
-}
-
-function cdayf() {
-    
-    return;
-
-    if ((ccy>sccy)|((ccy==sccy)&&(ccm>=sccm)))
-	    return;
-    else {
-	    ccy=sccy;
-	    ccm=sccm;
-	    cfd=scfd;
-	}
-}
diff --git a/scp/js/scp.js b/scp/js/scp.js
index 071c63ff82cb339fdfc8517136672910efeb41f3..b31f673f0d9f7119768846bae078d11770ed18fc 100644
--- a/scp/js/scp.js
+++ b/scp/js/scp.js
@@ -185,6 +185,14 @@ $(document).ready(function(){
         },
         'json')
         .error( function() {});
+    /* Datepicker */
+
+    $('.dp').datepicker({
+        numberOfMonths: 2,
+        showButtonPanel: true,
+        buttonImage: './images/cal.png',
+        showOn:'both'
+     });
 
     /* NicEdit richtext init */
     var rtes = $('.richtext');
diff --git a/scp/logout.php b/scp/logout.php
index e02e4be1609d387d43b3e59d1693a291d80677cb..32d62d14abb29363df9a7da033a1f0873821cbc9 100644
--- a/scp/logout.php
+++ b/scp/logout.php
@@ -15,7 +15,9 @@
     vim: expandtab sw=4 ts=4 sts=4:
 **********************************************************************/
 require('staff.inc.php');
-Sys::log(LOG_DEBUG,'Staff logout',sprintf("%s logged out [%s]",$thisstaff->getUserName(),$_SERVER['REMOTE_ADDR'])); //Debug.
+$ost->logDebug('Staff logout',
+        sprintf("%s logged out [%s]", 
+            $thisstaff->getUserName(), $_SERVER['REMOTE_ADDR'])); //Debug.
 $_SESSION['_staff']=array();
 session_unset();
 session_destroy();
diff --git a/scp/profile.php b/scp/profile.php
index f9dd42a5f19a597e6b40c0e68774dce58d2a4a02..e6506fa6ece8bd0686550cae4810e17a2c76cd6f 100644
--- a/scp/profile.php
+++ b/scp/profile.php
@@ -29,7 +29,7 @@ if(!$errors && $_POST) { //Handle post
         $thisstaff->reload();
         $staff->reload();
         $_SESSION['TZ_OFFSET']=$thisstaff->getTZoffset();
-        $_SESSION['daylight']=$thisstaff->observeDaylight();
+        $_SESSION['TZ_DST']=$thisstaff->observeDaylight();
     }elseif(!$errors['err'])
         $errors['err']='Profile update error. Try correcting the errors below and try again!';
 }
diff --git a/scp/settings.php b/scp/settings.php
index d7809d63751039c61639efd448c5718a888cb7ac..9058fe42ca52c4f9b428bbc52f2ed2cb61f80a8a 100644
--- a/scp/settings.php
+++ b/scp/settings.php
@@ -57,7 +57,7 @@ require(STAFFINC_DIR.'header.inc.php');
     </form>
 </div>
 <?php
-$config=($errors && $_POST)?Format::input($_POST):Format::htmlchars($cfg->getConfig());
+$config=($errors && $_POST)?Format::input($_POST):Format::htmlchars($cfg->getConfigInfo());
 include_once(STAFFINC_DIR."settings-$target.inc.php");
 include_once(STAFFINC_DIR.'footer.inc.php');
 ?>
diff --git a/scp/staff.inc.php b/scp/staff.inc.php
index 7a4dfb9e3a596fcc480894c60ecf2bede2304181..a28cf1d63a288ad39697527bd10c7d4fbbd28611 100644
--- a/scp/staff.inc.php
+++ b/scp/staff.inc.php
@@ -71,7 +71,7 @@ if(!$thisstaff->isAdmin()) {
     }
 
     //Staff are not allowed to login in offline mode!!
-    if($cfg->isHelpDeskOffline() || $cfg->isUpgradePending()) {
+    if(!$ost->isSystemOffline() || $ost->isUpgradePending()) {
         staffLoginPage('System Offline');
         exit;
     }
@@ -83,17 +83,16 @@ $thisstaff->refreshSession();
 /******* SET STAFF DEFAULTS **********/
 //Set staff's timezone offset.
 $_SESSION['TZ_OFFSET']=$thisstaff->getTZoffset();
-$_SESSION['daylight']=$thisstaff->observeDaylight();
+$_SESSION['TZ_DST']=$thisstaff->observeDaylight();
 
-define('AUTO_REFRESH_RATE',$thisstaff->getRefreshRate()*60);
-define('PAGE_LIMIT',$thisstaff->getPageLimit()?$thisstaff->getPageLimit():DEFAULT_PAGE_LIMIT);
+define('PAGE_LIMIT', $thisstaff->getPageLimit()?$thisstaff->getPageLimit():DEFAULT_PAGE_LIMIT);
 
 //Clear some vars. we use in all pages.
 $errors=array();
 $msg=$warn=$sysnotice='';
 $tabs=array();
 $submenu=array();
-if($cfg->isUpgradePending()) {
+if($ost->isUpgradePending()) {
     $errors['err']=$sysnotice='System upgrade is pending <a href="../setup/upgrade.php">Upgrade Now</a>';
 } elseif($cfg->isHelpDeskOffline()) {
     $sysnotice='<strong>System is set to offline mode</strong> - Client interface is disabled and ONLY admins can access staff control panel.';
diff --git a/scp/tickets.php b/scp/tickets.php
index e9a13f3efcf1a5b5d811a32a29310a7b94102510..6f40db445952fe6bbedc063a20a6c2a1be1539af 100644
--- a/scp/tickets.php
+++ b/scp/tickets.php
@@ -487,7 +487,7 @@ if($ticket) {
 
     //set refresh rate if the user has it configured
     if(!$_POST && $_REQUEST['a']!='search'  && ($min=$thisstaff->getRefreshRate()))
-        define('AUTO_REFRESH', $min*60); 
+        $ost->addExtraHeader('<meta http-equiv="refresh" content="'.($min*60).'" />');
 }
 
 require_once(STAFFINC_DIR.'header.inc.php');
diff --git a/setup/inc/class.upgrader.php b/setup/inc/class.upgrader.php
index 73af7e6066cddf41140d7bd6f2c2618431dfe83f..891d472d9264a78501bac8ec6d7a4d28abf8553c 100644
--- a/setup/inc/class.upgrader.php
+++ b/setup/inc/class.upgrader.php
@@ -50,8 +50,9 @@ class Upgrader extends SetupWizard {
     }
 
     function onError($error) {
+        global $ost;
 
-        Sys::log(LOG_ERR, 'Upgrader Error', $error);
+        $ost->logError('Upgrader Error', $error);
         $this->setError($error);
         $this->setState('aborted');
     }
@@ -191,6 +192,7 @@ class Upgrader extends SetupWizard {
     }
     
     function upgrade() {
+        global $ost;
 
         if($this->getPendingTasks() || !($patches=$this->getPatches()))
             return false;
@@ -209,7 +211,7 @@ class Upgrader extends SetupWizard {
             if(($info = $this->readPatchInfo($patch)) && $info['version'])
                 $logMsg.= ' ('.$info['version'].') ';
 
-            Sys::log(LOG_DEBUG, 'Upgrader - Patch applied', $logMsg);
+            $ost->logDebug('Upgrader - Patch applied', $logMsg);
             
             //Check if the said patch has scripted tasks
             if(!($tasks=$this->getTasksForPatch($phash)))
diff --git a/setup/p.php b/setup/p.php
index babeebb866f198e7fc78516a34133164d72a9b47..51c7055f257559099fd600ef12c31e882605873d 100644
--- a/setup/p.php
+++ b/setup/p.php
@@ -41,19 +41,19 @@ if(!$_SESSION['ost_upgrader'][$upgrader->getShash()]['progress']) {
 }
 
 if($upgrader->getNumPendingTasks()) {
-    if($upgrader->doTasks() && !$upgrader->getNumPendingTasks() && $cfg->isUpgradePending()) {
+    if($upgrader->doTasks() && !$upgrader->getNumPendingTasks() && $ost->isUpgradePending()) {
         //Just reporting done...with tasks - break in between patches!
         header("HTTP/1.1 304 Not Modified");
         exit;
     }
-} elseif($cfg->isUpgradePending() && $upgrader->isUpgradable()) {
+} elseif($ost->isUpgradePending() && $upgrader->isUpgradable()) {
     $version = $upgrader->getNextVersion();
     if($upgrader->upgrade()) {
         //We're simply reporting progress here - call back will report next action'
         Http::response(200, "Upgraded to $version ... post-upgrade checks!");
         exit;
     }
-} elseif(!$cfg->isUpgradePending()) {
+} elseif(!$ost->isUpgradePending()) {
     $upgrader->setState('done');
     session_write_close();
     header("HTTP/1.1 304 Not Modified");
diff --git a/setup/upgrade.php b/setup/upgrade.php
index 0406383707cfe245fd11aae9323ee1422d6d679e..e5fd21084ccb534167d681ee6288793d5a683296 100644
--- a/setup/upgrade.php
+++ b/setup/upgrade.php
@@ -48,7 +48,7 @@ if($_POST && $_POST['s'] && !$upgrader->isAborted()) {
     switch(strtolower($_POST['s'])) {
         case 'prereq':
             //XXX: check if it's upgradable version??
-            if(!$cfg->isUpgradePending())
+            if(!$ost->isUpgradePending())
                 $errors['err']=' Nothing to do! System already upgraded to the current version';
             elseif(!$upgrader->isUpgradable())
                 $errors['err']='The upgrader does NOT support upgrading from the current vesion!';
@@ -60,9 +60,9 @@ if($_POST && $_POST['s'] && !$upgrader->isAborted()) {
         case 'upgrade': //Manual upgrade.... when JS (ajax) is not supported.
             if($upgrader->getNumPendingTasks()) {
                 $upgrader->doTasks();
-            } elseif($cfg->isUpgradePending() && $upgrader->isUpgradable()) {
+            } elseif($ost->isUpgradePending() && $upgrader->isUpgradable()) {
                 $upgrader->upgrade();
-            } elseif(!$cfg->isUpgradePending()) {
+            } elseif(!$ost->isUpgradePending()) {
                 $upgrader->setState('done');
             }
 
@@ -89,7 +89,7 @@ switch(strtolower($upgrader->getState())) {
         $inc='upgrade-prereq.inc.php';
         if($upgrader->isAborted())
             $inc='upgrade-aborted.inc.php';
-        elseif(!$cfg->isUpgradePending())
+        elseif(!$ost->isUpgradePending())
             $errors['err']='Nothing to do! System already upgraded to the latest version';
         elseif(!$upgrader->isUpgradable())
             $errors['err']='The upgrader does NOT support upgrading from the current vesion!';