var DozoryTopPanel = {

        _pointerX: function(event) {
                return event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
        },

        _pointerY: function(event) {
                return event.pageY || (event.clientY+ (document.documentElement.scrollTop || document.body.scrollTop));
        },

        makeHandler: function (func,id) {
                return function(event) {
                        return func(event || window.event,id);
                }
        },

        showLoginLink: true,

        disableLoginLink : function (){
          this.showLoginLink = false;
        },

        styles : new Array(
            { selector : 'body', declaration : 'margin:0 0 0 0; padding:0 0 0 0;' },

            { selector : '.doz_panel', declaration : 'background: url(http://dozory.ru/i/bg_topbar.jpg) top left; color: #636768; font-size: 11px;' },

            { selector : '.doz_top_item',     declaration : 'color: #636768; font-size: 11px; font-weight: normal; font-family: tahoma,verdana,arial,sans-serif; text-decoration: none; cursor: pointer' },
            { selector : '.doz_top_item_act', declaration : 'color: #636768; font-size: 11px; font-weight: normal; font-family: tahoma,verdana,arial,sans-serif; text-decoration: none; cursor: pointer' },


            { selector : '.doz_submenu_container', declaration : 'margin-top: -5px; padding: 5px 2px 10px 2px; z-index: 100; '},
            { selector : '.doz_submenu_block',     declaration : 'border-left: 1px solid #9daab3; border-right: 1px solid #9daab3; border-bottom: 1px solid #9daab3; background: #dde2e6;' },
            { selector : '.doz_submenu_item',      declaration : 'color: #636768 !important; font-size: 11px !important; font-weight: normal !important; font-family: tahoma,verdana,arial,sans-serif !important; text-decoration: none !important; cursor: pointer' },
            { selector : '.doz_submenu_item_act',  declaration : 'color: white !important; font-size: 11px !important; font-weight: normal !important; font-family: tahoma,verdana,arial,sans-serif !important; text-decoration: none !important; cursor: pointer; background: #AEB4C2; !important' },
            
            { selector : 'TABLE.doz_top_item TD.left',   declaration : 'background: none'  },
            { selector : 'TABLE.doz_top_item TD.middle', declaration : 'background: none' },
            { selector : 'TABLE.doz_top_item TD.right',  declaration : 'background: none' },

            { selector : 'TABLE.doz_top_item_act TD.left',   declaration : 'background: url(http://dozory.ru/b_left.gif);' },
            { selector : 'TABLE.doz_top_item_act TD.middle', declaration : 'background: url(http://dozory.ru/b_middle.gif); padding-top: 2px;' },
            { selector : 'TABLE.doz_top_item_act TD.right',  declaration : 'background: url(http://dozory.ru/b_right.gif);' }
              
        ),


        templates: {
              dozory_toppanel_head : '<DIV style="width:100%;" id="DOZ_PANEL_CONT"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td class="doz_panel"><a href="http://dozory.ru/"><img src="http://dozory.ru/i/logo_topbar.jpg" width="135" height="32" alt="" border="0"></a></td><td width="100%" nowrap valign=top class="doz_panel" id="logo"><table border="0" cellspacing="0" cellpadding="0"><tr><td size="1"><img src="http://dozory.ru/img/zero.gif" width="1" height="32"></td>',


             dozory_toppanel_lfoot : '</tr></table></td><td width="1%" nowrap align=right valign=top style="padding-top: 8px; padding-right: 15px;" class="doz_panel"><a href="http://game.dozory.ru/cgi-bin/login.cgi" style="color:#636768; font-size: 11px; font-weight: bold;  text-decoration: none;">ВХОД В СУМРАК</a></td></tr></table></DIV>',

             dozory_toppanel_foot : '</tr></table></td><td width="1%" nowrap align=right valign=top style="padding-top: 8px; padding-right: 15px;" class="doz_panel">&nbsp;</td></tr></table></DIV>',


             menu_element : '<td onMouseOver="DozoryTopPanel.showSubmenu(%NUM%,event);" onMouseOut="DozoryTopPanel.hideSubmenu(%NUM%,event);" class="doz_top_item" id="%ID%"><table cellspacing="0" cellpadding="0" class="doz_top_item"><tr><td class="left"><img src="http://dozory.ru/img/zero.gif" width="2" height="27"></td><td class="middle">&nbsp;%CAPTION%&nbsp;</td><td class="right"><img src="http://dozory.ru/img/zero.gif" width="2" height="27"></td></tr></table></td>',
            

             submenu_element : '<tr><td class="doz_submenu_item" onMouseOver="DozoryTopPanel.onSubmenuItem(\'%ID%\')" onClick="document.location.href=\'%LINK%\';" onMouseOut="DozoryTopPanel.offSubmenuItem(\'%ID%\')" id="%ID%">&nbsp;<a id="%ID%a" class="doz_submenu_item" href="%LINK%">%CAPTION%</a>&nbsp;</td></tr>'
        },


        menu_items: new Array(),
        created_submenu: new Array(),

        initStyles : function () {
             if(document.styleSheets.length == 0){ 
                document.write('<style></style>');
             }

             for(var i=0; i< this.styles.length; i++){
               if(document.styleSheets[0].insertRule)
                document.styleSheets[0].insertRule(this.styles[i].selector + ' { ' + this.styles[i].declaration + ' } ', 0)
               else if( document.styleSheets[0].addRule )
                document.styleSheets[0].addRule(this.styles[i].selector,this.styles[i].declaration,0)
             }

        },

        head: function() {
           return this.templates['dozory_toppanel_head']
        },

        content: function() {

          var res = '';
          for(var i=0; i< this.menu_items.length; i++){

              var str = this.templates['menu_element'];
              str = str.replace(/%ID%/g,'menu_'+i);
              str = str.replace(/%NUM%/g,i);
              str = str.replace(/%CAPTION%/g,this.menu_items[i][0]);

              res = res + str;
          }

          return res;
        },

        
        foot: function() {
           var res = '';
           if(this.showLoginLink)
             res = this.templates['dozory_toppanel_lfoot']
           else
             res = this.templates['dozory_toppanel_foot'];

           return res;
        },



        add_menu_item: function(name,subitems){
           this.menu_items.push(new Array(name,subitems));
        },


        initMenu: function(){
           this.add_menu_item('Информация об игре',new Array(
                                              { link : 'http://dozory.ru/cgi-bin/index.cgi', caption : 'Новостная лента' },
                                              { link : 'http://manual.dozory.ru', caption : 'Мануал Дозоры.ру' },
                                              { link : 'http://forum.dozory.ru/', caption : 'Форум' },
                                              { link : 'http://library.dozory.ru/', caption : 'Библиотека' },
                                              { link : 'http://manual.dozory.ru/faq.html', caption : 'FAQ (ЧаВо?)' },
                                              { link : 'http://inquisition.dozory.ru/investigation.cgi', caption : 'Формуляр Инквизиции' },
											  { link : 'http://support.dozory.ru/', caption : 'Техподдержка' }
                                                                     ));
           this.add_menu_item('Организации',new Array(
                                              { link : 'http://nd-dozor.ru/', caption : 'Ночной Дозор' },
                                              { link : 'http://www.dd-msk.ru/', caption : 'Дневной Дозор' },
                                              { link : 'http://inquisition.dozory.ru/', caption : 'Инквизиция' },
                                              { link : 'http://orgs.dozory.ru/', caption : 'Список всех организаций' }
                                                             ));
          this.add_menu_item('Дополнительные сервисы',new Array(
                                              { link : 'http://profiles.dozory.ru/', caption : 'Информация о персонажах' },
                                              { link : 'http://logs.dozory.ru/', caption : 'Логи боев. Поиск.' },
                                              { link : 'http://api.dozory.ru/', caption : 'API интерфейс к игре' },
                                              { link : 'http://game.dozory.ru/cgi-bin/rescue.cgi', caption : 'Интерфейс спасения' }
                                                                       ));
          this.add_menu_item('Платные услуги',new Array(
                                              /*{ link : 'http://dealers.dozory.ru/', caption : 'Коммерческая служба' },*/
                                              { link : 'http://pay.dozory.ru/', caption : 'Список платных услуг' },
                                              { link : 'http://sms.dozory.ru/', caption : 'Услуги по SMS' }
                                                              ));
/*
          this.add_menu_item('<strong style="color: #4C5660">Юбилей Дозоров</strong>',new Array(
                                              { link : 'http://party.dozory.ru/', caption : '2 Года в Сумраке' },
                                              { link : 'http://party.dozory.ru/party.html', caption : 'Запрещенная вечеринка' },
                                              { link : 'http://party.dozory.ru/konkurs.html', caption : 'Конкурс Красоты' },
                                              { link : 'http://dozory.ru/bbs/viewtopic.php?p=273560#273560',  caption : 'Обсудить на форуме' }
                                                              ));
*/
        },

        write: function(flag) {
           
           this.initStyles();
           if(!flag){
              this.initMenu();
           }
           
           document.write( this.head() + this.content() + this.foot() ); 
        },



        showSubmenu : function (num,event) {
           this.hideAll(num);
           if(this.created_submenu[num] == null){
             this.createSubmenu(num);
           }

          var submenu = this.created_submenu[num];

          var td = document.getElementById('menu_'+num);
          td.firstChild.className='doz_top_item_act';
//          td.className='doz_top_item_act';


          var logo = document.getElementById('logo');

          submenu.style.position = 'absolute';
          submenu.style.left = (td.offsetLeft+logo.offsetLeft-1)+'px';
          submenu.style.top='32px';
          submenu.style.display = 'block';

        },




        pointerOutMenu : function (num,event){
 
           var submenu = this.created_submenu[num];

           var pointerX = this._pointerX(event);
           var pointerY = this._pointerY(event);
 
           var result = pointerX <= submenu.offsetLeft || pointerX >= (submenu.offsetLeft + submenu.offsetWidth ) || pointerY < submenu.offsetTop  || pointerY >= (submenu.offsetTop+submenu.offsetHeight);
           return result;

        },

        hideSubmenu : function (num,event){
           var submenu = this.created_submenu[num];

           if(DozoryTopPanel.pointerOutMenu(num,event)){
             submenu.style.display = 'none';
             var td = document.getElementById('menu_'+num);
             td.firstChild.className='doz_top_item';
//             td.className='doz_top_item';
           }else{
             submenu.onmouseout = this.makeHandler(
                                         function (event,id) {
                                              if (DozoryTopPanel.pointerOutMenu(id,event)) {
                                                    DozoryTopPanel.hideSubmenu(id,event);
                                              }
                                          },num);
           }
        },
        
        hideAll: function (num){
        	for (i = 0; i<this.created_submenu.length; i++) {
        		if (this.created_submenu[i] != null && i != num){
	        		this.created_submenu[i].style.display = 'none';
    	    		var td = document.getElementById('menu_'+i);
        	   		td.firstChild.className='doz_top_item';
        		}
        	}
        },

        createSubmenu : function (num){
          var submenu_container = document.createElement('div');
              submenu_container.className = 'doz_submenu_container';
              submenu_container.style.display = 'none';
              submenu_container.id = 'submenu_'+num;
              
		  var submenu = document.createElement('div'); 
		  	  submenu.className = 'doz_submenu_block';
		  
          sitems = this.menu_items[num][1];
          res = '<table>';
          for(var i=0; i< sitems.length; i++){
             var str = this.templates['submenu_element'];

             str = str.replace(/%ID%/g,'submenu_'+num+'_'+i);
             str = str.replace(/%CAPTION%/g,sitems[i].caption);
             str = str.replace(/%LINK%/g,sitems[i].link);
             res = res + str;
          }
          res = res + '</table>';
          submenu.innerHTML = res;
          
          var c = window.document.getElementById('DOZ_PANEL_CONT');

          if(c != null){  
           c.appendChild(submenu_container);
           submenu_container.appendChild(submenu);          
           this.created_submenu[num] = submenu_container;
          }

        },

        onSubmenuItem : function (id){
          document.getElementById(id).className = 'doz_submenu_item_act';
          document.getElementById(id+'a').className = 'doz_submenu_item_act';
        },

        offSubmenuItem : function (id){
          document.getElementById(id).className = 'doz_submenu_item';
          document.getElementById(id+'a').className = 'doz_submenu_item';
        }

  }

