<?  
    DEFINE("DEBUG_PANEL", 0);

    header("Cache-Control: no-cache");

    session_start();

    if(count($_GET) > 0) {
        $_SESSION["get"] = $_GET;
        $dir = dirname($_SERVER["PHP_SELF"]);
        if(($dir == "/") || ($dir == "\\")) {
            $dir = "";
        }
        header("Location: http://".$_SERVER["SERVER_NAME"].$dir);
        die();
    }

    require_once("conf/config.php");
    require_once("core/system.php");
    require_once("core/mysql.php");

    $db = new mysql_db();
    if(!$db->connect(_DB_HOST, _DB_NAME, _DB_USER, _DB_PASS)) {
        die("DB connection error.");
    }

    $widgets = parse_ini_file("widgets/widgets.ini", true);


    $outJs = "var/code.js";
    $jsList = array(
        "js/system.js",
        "js/request.js",
        "js/xmlparser.js",
        "js/utils.js",
        "js/widget.js",
        "js/drag.js",
        "js/kernel.js",
        "js/desktop.js"
    );

    foreach($widgets as $k => $v) {
        $jsList[] = "widgets/".trim($k)."/widget.js";
    }


    if(file_exists($outJs)) {
        $clm = filemtime($outJs);
    } else {
        $clm = 0;
    }

    $needRecompile = false;
    for($i=0; $i<count($jsList); $i++) {
        if(filemtime($jsList[$i]) > $clm) {
            $needRecompile = true;
            break;
        }
    }

    $offset = abs(crc32($_SERVER["SERVER_NAME"]) % 500);
    $words = array("getNoCache","getTransportObj","getXML","defaultProfile","domModel","modelDefaultSettings","elements","isReduced","isSettingsReduced","profile","isPreview","buildWindow","buildInterface","onOpen","buildDomModel","onBuildInterface","isForceClose","forceClose","setTitle","checkMouseInOut","switchSize","onShow","hideSettings","onHide","switchSettings","showSettings","onShowSettings","settingsSetTitle","onDrag","onSelectColor","onSelectFont","onSelectFontSize","timerHandler","dispatchMsg","hideElement","showElement","widgts","addWidget","freeWidget","runWidget","timers","processTimer","stopTimer","parseLangXML","getHashList","newFeedUrl","applyTheme","isMenuShow","switchMenu","activePage","closeCurrentPage","editTitle","columners","tabOptionsShown","getNewTabNumber","addNewTab","defaultPanelsCount","getPanelsDom","renderTab","showTab","getTabIconSrc","belongTabInfo","onTabDragStart","onTabDragOver","onTabDragStop","activeTab","hideTab","hideTabOptions","showTabOptions","tabIcons","renameTab","setTabIcon","deleteTabIcon","closeTab","setPanelsCount","getPanelsCount","getPanel","getTinyPanel","savePanels","getBelongPanel","getWindowAtPos","startArea","stopArea","processArea","putWindow","showAll","hideAll","wakeUp","addFeedDispatch","addToFavorites","domContent","showRegform","hideRegform","tryLogin","tryRegister","checkEmail","checkPassword","signIn","loadUser","saveUser","registerUser","registerWidget","saveProfile","loadProfile","domModelContent","domModelAdditional","menuItemId","getMenuItemId","switchCategory","renderCategory","switchPanel","hideItemMenu","closePreview","closeAddFeedPanel","openWidget","hideHint","oldDisableOnClosePrompt","addToDesktop","currentHint","showHint","setAddFeedStatus","addFeedPanelVisible","showAddFeedPanel","addFeed","registerFeed","activeItemId","showItemControl","hideItemControl","showItemMenu","showRenameItemSection","getItemNum","showDeleteItemSection","renameItem","deleteItem","tmpIcons","themeBackground","applyBackgound","selectedBackground","testBackgroundImg","testBackgroundColor","saveBackground","delBackground","currentPopup","showPopup","closePopup","selectColor","selectFont","selectFontSize","renderThemes","setCurrentTheme","setTheme","showText","applyText","sendFeedback","domSendToFriend","doSend","domSettings","lastRefresh","isLoading","isInReader","setUrl","setOpenDirectly","setNewsCount","showChannelTitle","renderChannel","setPeriod","openChannel","getItemsCount","processItemRead","processItemUnread","getReadedItemsCount","lastFeed","getItemMd5","showChannel","isReaded","showError","openSite","setReaded","unsetReaded","channelLastRefresh","buildChannel","widgetId","readFeed","updateTitle","readAll","unReadAll","openFlash","isUpdating","switchSection","renderContactList","addContact","deleteContact","startNewMessage","replyTo","sendMessage","firstRenderMessages","renderMessages","clearMessages","showMail","fullCount","setConfigState","switchMailsContent","openInbox","setPort","isProfileEmpty","setContent","totalMessages","activeTag","applyTag","closeEdit","uploadFile","importError","importFromUrl","tmpFile","parseBookmarks","addBookmark","renderTags","editBookmarkId","isEditOpen","openEdit","processUpdate","updateBookmark","deleteBookmarks","processAdd","getBookmarksByTagId","deleteBookmark","renderItems","renderItem","addItem","switchItem","moveItemUp","swapItems","moveItemDown","editItem","contentDomWebnote","editText","switchFlashCategory","loadFlash","openPlayer","stopFlash","renderFlashCategory","tagUrl","setLayout","renderPhotos","setTarget","setTags","curPhoto","showBigPhoto","showAllPhotos","showPrevPhoto","showNextPhoto","openBigPhoto","openPhoto","showPhotos","setChannel","setCount","renderContent","parseContent","setUnit","renderWeather","loadCities","showCities","setCity","toCelcius","getTemp","showWeather","showServerTab","setServer","goSearch","navHome","setHomePage","formatUrl");
    $replaces = array();
    for($i = 0; $i<count($words); $i++) {
        $replaces[$i] = "d".($i + $offset);
    }

    if($needRecompile) {
        $f = fopen($outJs, "w+");
        for($i=0; $i<count($jsList); $i++) {
            $ln = file($jsList[$i]);
            for($l=0; $l<count($ln); $l++) {
                $st = trim($ln[$l]);
                if($st != "") {
                    $st = str_replace($words, $replaces, $st);
                    fwrite($f, $st."\n");
                }
            }
        }
        fclose($f);
    }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="static/client.css">

<BODY onload="start()">

<div id="DEBUG" style="display: <?=(DEBUG_PANEL ? 'block' : 'none');?>; position: absolute; width: 300px; height: 500px; right: 0; bottom: 0; background: #AABBFF; overflow: auto;"></div>

<div class="loading_box" id="loading_note"><? includeTpl("templates/includes/splash.tpl"); ?></div>

<div class="loading_spinner" id="loading_spinner">
    <img src="static/client/spinner.gif">
</div>

<!-- <div style="position: absolute; left:0; top: 0; z-index: 10000000;" id="dbg"></div>-->

<div id="page_header" class="page_header" style="display: none;"><? includeTpl("templates/includes/header.tpl"); ?></div>
<div id="desktop_body"></div>

<?
    $menuStruct = file("widgets/mainmenu.ini");
    $menuList = array();
    for($i=0; $i<count($menuStruct); $i++) {
        $w = trim($menuStruct[$i]);
        if(strpos($w, ";") === false) {
            if($w == "-") {
                $menuList[] = "\"-\"";
            } else {
                $menuList[] = "{ title: \"".$widgets[$w]["title"]."\", className: \"".$widgets[$w]["className"]."\" }";
            }
        }
    }

    echo "<script language=\"Javascript\">\n";
    // constants
    echo "baseUrl = \"".dirname($_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"])."/\";\n";

    // GET vars
    $gvars = isset($_SESSION["get"]) ? $_SESSION["get"] : array();
    echo "_GET = ".getJsCode($gvars).";\n";
    unset($_SESSION["get"]);


    // session user
    echo "session_user = ".(isset($_SESSION["logged_user"]) ? getJsCode($_SESSION["logged_user"]) : "false")."\n";

    // menu items
    if($menuList) {
        echo "menuWidgets = [ ". implode(",", $menuList) ." ]\n";
    }

    // websearch servers
    $ws_serves = $db->query("SELECT * FROM "._DB_TABLE_PREFIX."websearch");
    echo "websearch_servers = ".getJsCode($ws_serves).";\n";
    

    // Languages
    if (isset($_COOKIE['lng']))
       $lang = strtolower($_COOKIE['lng']);
    else
       $lang = 'en';

    $desktopLangs = null;
    $langs = parse_ini_file("lang/langs.ini", true);
    foreach($langs as $k => $v) {
        $desktopLangs[] = "&nbsp;<a class=footer_link href=\"javascript:loc.swapLang(\\'".
                          $v['langid'].
                          "\\')\"><img style=\"height: 12px; border: 0; vertical-align: bottom;\" src=\"static/flags/".$v['langid'].".gif\"/>&nbsp;".$v['display']."</a>&nbsp;";
    }
    if($desktopLangs) {
        echo "desktopLangsHTML = '". implode("-", $desktopLangs) ."';\n";

    }


    // custom pages
    $custom_pages = $db->query("SELECT * FROM "._DB_TABLE_PREFIX."custompages WHERE lang='".$lang."'");
    if(isset($custom_pages["id"])) {
        $custom_pages = array($custom_pages);
    }
    echo "custom_pages = ".getJsCode($custom_pages).";\n";

    if (is_array($custom_pages))
      for($i=0;$i<count($custom_pages);$i++) {
        $page = $custom_pages[$i];
        $c_pages[] = "&nbsp;<a href=\"javascript:void(0);\" onClick=\"custompage.setData(custom_pages[$i].title, custom_pages[$i].content); desktop.showPage(\\'custompage\\');\">".$page["title"]."</a>&nbsp;";
      }

    if($c_pages)
      echo "customPagesHTML = '". implode("|", $c_pages) ."';\n";
    else
      echo "customPagesHTML ='';\n";

    echo "</script>";


    if($_SERVER["SERVER_NAME"] != "jaws") {
        includeJs($outJs);
    } else {
        for($i=0; $i<count($jsList); $i++) {
            includeJs($jsList[$i]);
        }
    }
?>




<script type="text/javascript">
function start() {
    function showJSError(msg,url,l) {
        var msg = "There was an error on this page.\n\n"+
                  "Error: " + msg + "\n"+
                  "URL: " + url + "\n"+
                  "Line: " + l + "\n\n"+
                  "Click OK to continue.\n\n";
        alert(msg);
        return false;
    }
//    if(baseUrl != "jaws1") {
        window.onerror = showJSError;
//    }
    startPage();
}
</script>


<div id="page_footer" class="page_footer" style="display: none;"><? includeTpl("templates/includes/footer.tpl"); ?> </div>

</BODY>
</HTML>
