/*  News Reader Application Object, written for HKPCUG Webnews CS Edition
 *  requires prototype framework
 *  (c) 2006 Tamcy
/*--------------------------------------------------------------------------*/

 // From http://www.quirksmode.org/viewport/compatibility.html
 function getDocumentFrameDimension()
 {
    var x,y;
    if (self.innerHeight) // all except Explorer
    {
        x = self.innerWidth;
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight)
        // Explorer 6 Strict Mode
    {
        x = document.documentElement.clientWidth;
        y = document.documentElement.clientHeight;
    }
    else if (document.body) // other Explorers
    {
        x = document.body.clientWidth;
        y = document.body.clientHeight;
    }
    var a = {width: x, height: y};
    return a;
 }

 function getDocumentViewportHeight()
 {
    return getDocumentFrameDimension().height;
 }

 function getDocumentViewportWidth()
 {
    return getDocumentFrameDimension().width;
 }

 var NewsReaderApp = {
    Copyright: '(c)2006 Tamcy',

    currentServer : '',
    currentGroup : '',
    groupData : {}, 
    currentArticle : 0,
    mode : 'view',
    cache : {},
	isIE : false,

    start : function() {

       addLog('Starting Application');

        if ($('ArticleListNavBar').offsetHeight)
           AppLayout.listNavbarHeight = $('ArticleListNavBar').offsetHeight;
        
       this.splitter1 = new Splitter();
       this.splitter1.register($('MainPanelResizeLeft'), $('MainPaneLeft'), 'v', function(newsize) { NewsReaderApp.onGroupListResize(newsize); });
	   this.splitter1.limitMax = true;
	   this.splitter1.limitMaxValue = 300;

       this.splitter2 = new Splitter();
       this.splitter2.register($('MainPanelArticleListResizer'), $('ListviewPane'), 'h', function(newsize) { NewsReaderApp.onListviewResize(newsize); });
	   this.splitter2.limitMin = true;
	   this.splitter2.limitMinValue = 50;
	   this.splitter2.limitMax = true;

	   this.resizeControls();

       Event.observe(document, 'keypress', this.onKeyPress.bindAsEventListener(this), false);

    },

	setIE : function()
	{
		this.isIE = true;
	    addLog('is ie');
	},

    onKeyPress : function(e)
    {
      if (this.mode != 'view')
        return true;
      
      var code = 0;
      if (!e.charCode)
      {
        //IE
        code = e.keyCode; 
        addLog('Keypressed '+code);
      }
      else
      {
        if (!e.ctrlKey && !e.altKey && !e.shiftKey )
        {
          code = e.which;
          addLog('Keypressed '+e.keyCode);
          addLog('Keypressed '+e.which);
          addLog('Keypressed '+e.charCode);
        }
      }

      if (code == 0)
        return true;

      switch (code)
      {
        //z
        case 90: case 122:
          NewsReaderApp.navArticleHeaders('last');
          break;
        //x
        case 88: case 120:
          NewsReaderApp.navArticleHeaders('prev');
          break;
        //c
        case 67: case 99:
          NewsReaderApp.navArticleHeaders('next');
          break;
        //v
        case 86: case 118:
          NewsReaderApp.navArticleHeaders('first');
          break;
        //W : 
        case 87: case 119:
          NewsReaderApp.doNewPost();
          break;
        //r : 
        case 82: case 114:
          NewsReaderApp.doReplyPost();
          break;
        //q : 
        case 81: case 113:
          if (this.currentArticle > 0)
          {
             var em = $('hidx-'+this.currentArticle);
             if (em)
             {
                var em2 = em.previousSibling;
                if (em2 && (match = em2.id.match(/^hidx-(.*)$/)))
                {
                  this.getArticleA(match[1]);
                }
             }
          }
          break;
        //a : 
        case 65: case 97:
          if (this.currentArticle > 0)
          {
             var em = $('hidx-'+this.currentArticle);
             if (em)
             {
                var em2 = em.nextSibling;
                if (em2 && (match = em2.id.match(/^hidx-(.*)$/)))
                {
                  this.getArticleA(match[1]);
                }
             }
          }
          else
          {
            var i = 0;
            var em = $('ArticleHeaderList').childNodes[i];
            while (em && em.nodeName.toLowerCase() != 'div') {
               i++;
               em = $('ArticleHeaderList').childNodes[i];
               // addLog(em.nodeName);
            }

            if (em)
            {
              if (em && (match = em.id.match(/^hidx-(.*)$/)))
                this.getArticleA(match[1]);
            }
          }
          break;
      }
    },

    confirmCancelPosting : function(msg)
    {
       if (!msg)
       {
          msg = '確定要放棄編輯中的文章？';
       }
       return confirm(msg);
    },
    
    onBeforeSelectArticle : function()
    {
        if (this.mode == 'posting')
           return this.confirmCancelPosting('選擇文章將會放棄現在編輯中的文章。你確定嗎？');

        return true;
    },

    onBeforeChangeGroup : function()
    {
        if (this.mode == 'posting')
           return this.confirmCancelPosting('轉換群組將會放棄現在編輯中的文章。你確定嗎？');

        return true;
    },

    initChangeGroup : function()
    {
       this.mode = 'view';
       this.clearMessagePaneContent();
    },

    onGroupListResize : function(newsize)
    {
        if (newsize)
        {
           addLog('Resizing group list to '+newsize);
           $('MainPaneLeft').style.width = newsize + 'px';
           $('MainPanelRight').style.marginLeft = (newsize+2) + 'px';
        }

       AppLayout.viewportWidth = getDocumentViewportWidth();
       addLog('viewportWidth = '+AppLayout.viewportWidth);

       AppLayout.workareaWidth = $('Workarea').offsetWidth;
       addLog('Workarea.width = '+$('Workarea').offsetWidth);

       AppLayout.leftPanelWidth = $('MainPaneLeft').offsetWidth;
       addLog('MainPanelLeft.width = '+$('MainPaneLeft').offsetWidth);
       
       var cWidth = AppLayout.viewportWidth-20-AppLayout.leftPanelWidth-$('MainPanelResizeLeft').offsetWidth-8;
       addLog('<b>cWidth = '+cWidth+'</b>');
       $('MessagePane').style.width=cWidth+'px';
    },

    onListviewResize : function(newsize)
    {

//if (navigator.appVersion.match(/\bMSIE\b/))

        if (newsize)
        {
           addLog('Resizing list view to '+newsize);
           $('ListviewPane').style.height = newsize + 'px';
           AppLayout.listViewPaneHeight = newsize;
        }

       // List area

         var lvpHeight = AppLayout.listViewPaneHeight;
         var lvpHeaderListHeight = AppLayout.listViewPaneHeight - AppLayout.listNavbarHeight;

         addLog('lvpHeight = '+lvpHeight);
         addLog('lvpHeaderListHeight = '+lvpHeaderListHeight);

       // Preview area

         var pHeight = getDocumentViewportHeight() - AppLayout.mainToolbarHeight - AppLayout.titleHeight - lvpHeight - 4;
         pHeight -= $('MainPanelArticleListResizer').offsetHeight; 
         addLog('pHeight = '+pHeight);
       
		 this.resizePostMessageBody(pHeight);

       //IE redraw
        $('MessagePane').style.display='none';
             $('ListviewPane').style.height = lvpHeight + 'px';  
             $('ArticleHeaderList').style.height = lvpHeaderListHeight + 'px'; //20px = navbar
             $('MessagePane').style.height = pHeight + 'px';  
        $('MessagePane').style.display='block';

//       AppLayout.listViewPaneHeight = $('ListviewPane').offsetHeight;
    },

	resizePostMessageBody : function(newMessagePaneHeight)
	{
//		if (this.isIE && this.mode == 'posting')
//		{
			addLog('Fixing posting issue');
			var x= newMessagePaneHeight;
			if ($('PostingHeader'))
			{
				var y = $('PostingHeader').offsetHeight;
			}

			if (x && y)
			{
				addLog('x='+x+',y='+y);
				$('TextAreaBody').style.height = (x - y) + 'px';
			}
//		}
	},

    resizeControls : function()
    { 
//       addLog('MainToolbar = '+$('MainToolbar').offsetHeight);

       var heightChanged = AppLayout.viewportHeight != getDocumentViewportHeight();
       var widthChanged = AppLayout.viewportWidth != getDocumentViewportWidth();

       if (heightChanged)
       {
           addLog('setting workarea height');
           AppLayout.viewportHeight = getDocumentViewportHeight();

           var fHeight = getDocumentViewportHeight() - AppLayout.titleHeight;

           $('Workarea').style.height = fHeight + 'px';
           addLog('=== workarea height = '+$('Workarea').style.height);

           $('MainPaneLeft').style.height = fHeight + 'px';
           addLog('=== MainPaneLeft height = '+$('MainPaneLeft').style.height);
			
		   this.splitter2.limitMaxValue = fHeight-100;

           addLog('fHeight='+fHeight);
           $('Panels').style.height = fHeight + 'px';

           // List area

             var lvpHeight = AppLayout.listViewPaneHeight;
             var lvpHeaderListHeight = AppLayout.listViewPaneHeight - AppLayout.listNavbarHeight;

             addLog('lvpHeight = '+lvpHeight);
             addLog('lvpHeaderListHeight = '+lvpHeaderListHeight);

           // Preview area

             var pHeight = getDocumentViewportHeight() - AppLayout.mainToolbarHeight - AppLayout.titleHeight - lvpHeight - 4;
             pHeight -= $('MainPanelArticleListResizer').offsetHeight; 
             addLog('pHeight = '+pHeight);

           // Action

             if (pHeight < 0)
             {
                lvpHeight += pHeight;
                lvpHeaderListHeight += pHeight;
                pHeight = 0;

                addLog('lvpHeight = '+lvpHeight);
                addLog('lvpHeaderListHeight = '+lvpHeaderListHeight);
                addLog('pHeight = '+pHeight);
             }

             $('ListviewPane').style.height = lvpHeight + 'px';  
             $('ArticleHeaderList').style.height = lvpHeaderListHeight + 'px'; //20px = navbar
             $('MessagePane').style.height = pHeight + 'px';  

			 addLog('**** Fixing posting issue ');
			 addLog(this.mode);
			 addLog(this.isIE);

			 this.resizePostMessageBody(pHeight);
/*
			 if (this.isIE && this.mode == 'posting')
			 {
				 addLog('Fixing posting issue');
				 //resize 
				 // var x = $('AddReplyFormContainer').offsetHeight;
				 var x= pHeight;
				 var y = $('PostingHeader').offsetHeight;

				 //alert('fix : '+x);
				 //alert('fix : '+y);

				 addLog('x='+x+',y='+y);
				 if (x && y)
				 {
				     $('TextAreaBody').style.height = (x - y) + 'px';
				 }
			 } */
       }

      if (widthChanged)
      {
         AppLayout.viewportWidth = getDocumentViewportWidth();
         addLog('viewportWidth = '+AppLayout.viewportWidth);

         //CHECK: offsetWidth in IE may not be resized yet.
         AppLayout.workareaWidth = $('Workarea').offsetWidth;
         addLog('Workarea.width = '+$('Workarea').offsetWidth);

         AppLayout.leftPanelWidth = $('MainPaneLeft').offsetWidth;
         addLog('MainPanelLeft.width = '+$('MainPaneLeft').offsetWidth);
         
         var cWidth = AppLayout.viewportWidth-20-AppLayout.leftPanelWidth-$('MainPanelResizeLeft').offsetWidth-8;
         addLog('<b>cWidth = '+cWidth+'</b>');
         $('MessagePane').style.width=cWidth+'px';
      }

    },

    articleListLoaded: function()
    { 
       this.currentArticle = 0;
       $('ArticleHeaderListToolbar').style.display='block';
       $('ArticleHeaderListStatus').style.display='block';
	   $('ArticleHeaderList').scrollTop = 0;
    },

    loadArticleHeaders : function(groupname, currentIndex, action)
    {
      if (!this.onBeforeChangeGroup())
      {
         return false;
      }

      this.initChangeGroup();

      var target = AppConfig.getArticleHeaders+'/'+this.currentServer+'/'+groupname+'/'+AppConfig.articlesPerPage;

      if (currentIndex)
      {
        target += '/'+currentIndex;

        if (action)
            target += '/'+action
      }

      new Ajax.Updater
          ('ArticleHeaderList', target,
           {asynchronous:true, 
            evalScripts:true, 
            onSuccess:function(request, json){NewsReaderApp.articleListLoaded()},
            onComplete:function(request, json){hideLoading()}, 
            onLoading:function(request, json){showLoading()}
           }
          );
      return false;
    },

    getArticleA : function(msgid)
    {
       this.getArticle(this.currentServer, this.currentGroup, msgid)
    },

    getArticle : function(server, group, msgid)
    {
      if (!this.onBeforeSelectArticle())
        return false;

      if (this.mode != 'view')
      {
         this.clearMessagePaneContent();
         this.mode = 'view';
      }

      var target = AppConfig.getArticle+'/'+server+'/'+group+'/'+msgid;

      addLog(target);

      new Ajax.Updater
          ('MessagePane', target,
           {asynchronous:true, 
            evalScripts:true, 
            onSuccess:function(request, json){  },
            onFailure:function(request, json) { NewsReaderApp.setSelectedArticle(0) },
            onComplete:function(request, json){ hideLoading() }, 
            onLoading:function(request, json){showLoading(); NewsReaderApp.setSelectedArticle(msgid); }
           }
          );
      return false;
    },

    navArticleHeaders : function(action)
    {
      if (!this.groupData['group'])
      {
        alert('No group selected!');
      }
      else
      {
        var target = AppConfig.getArticleHeaders+'/'+this.currentServer+'/'+this.groupData['group']+'/'+AppConfig.articlesPerPage;

        target += '/'+this.groupData['right']+'/'+action;
        addLog(target);

        new Ajax.Updater
            ('ArticleHeaderList', target,
             {asynchronous:true, evalScripts:true, onSuccess:function(request, json){NewsReaderApp.articleListLoaded()}}
            );

      }
      return false;
    },

    setHeaderListStatus : function(first, last, left, right)
    {
       addLog(first+'-'+last+', ['+left+'-'+right+']');
       this.groupData['left'] = left;
       this.groupData['right'] = right;
       this.groupData['first'] = first;
       this.groupData['last'] = last;

       $('ArticlesTotal').innerHTML = last-first+1;
       $('ArticlesLeft').innerHTML = left-first+1;
       $('ArticlesRight').innerHTML = right-first+1;
    },

    setGroupName : function(group, description)
    {
       if (this.groupData['group'])
          Element.removeClassName('group-'+this.groupData['group'], 'ItemSelected');

       addLog('['+group+']');
       this.groupData['group'] = group;
       this.currentGroup = group;

       Element.addClassName('group-'+this.groupData['group'], 'ItemSelected');

       $('MainGroupName').innerHTML = group;
       $('MainGroupDesc').innerHTML = description;
    },

    setSelectedArticle: function(msgid)
    {
       if (this.currentArticle > 0)
          Element.removeClassName('ArticleHeader-'+this.currentArticle, 'ItemSelected');

       this.currentArticle = msgid;

       if (this.currentArticle > 0)
		{
		   var e = $('ArticleHeader-'+this.currentArticle);
		   var headerList = $('ArticleHeaderList');

		   if (e)
		   {	
			   var itemY = Position.cumulativeOffset(e)[1] - Position.cumulativeOffset(headerList)[1];

			   var listRange = [headerList.scrollTop, headerList.scrollTop+headerList.offsetHeight];
			   if (itemY < listRange[0] || (itemY+e.offsetHeight) > listRange[1])
					headerList.scrollTop = (itemY-10 > 0)?(itemY-10):0;
		   }
           Element.addClassName('ArticleHeader-'+this.currentArticle, 'ItemSelected');
		}
    },

    clearMessagePaneContent : function()
    {
       $('MessagePane').innerHTML = '';
       this.cache['messagepane'] = '';
    },

    cacheMessagePaneContainer : function(mode)
    { 
      if (mode)
       if (NewsReaderApp.mode != mode)
        {
         addLog('Mode doesnt match, no caching');
         return;
        }
      addLog('cache msgpane!');
      this.cache['messagepane'] = $('MessagePane').innerHTML;
    },

    restoreMessagePaneContainer : function(mode)
    {
      if (mode)
       if (NewsReaderApp.mode != mode)
         return;

      addLog('restore msgpane!');
      $('MessagePane').innerHTML = this.cache['messagepane'];
    },

    doReplyPost : function()
    {
        if (this.currentServer && this.currentGroup && this.currentArticle > 0)
        {
            var target = AppConfig.actionReplyPost + '/' + this.currentServer + '/' + this.currentGroup + '/' + this.currentArticle;
            addLog(target);

            this.cacheMessagePaneContainer('view');

            new Ajax.Updater
                ('MessagePane', target,
                 {asynchronous:true, 
                  evalScripts:true, 
                  onSuccess:function(request, json){ NewsReaderApp.mode = 'posting' },
                  onComplete:function(request, json){hideLoading()}, 
                  onLoading:function(request, json){showLoading()}
                 }
                );
        }
        else
          alert('未選擇文章，無法回覆。');
    },

    doNewPost : function()
    {
        if (this.currentServer && this.currentGroup)
        {
            var target = AppConfig.actionNewPost + '/' + this.currentServer + '/' + this.currentGroup;
            addLog(target);

            this.cacheMessagePaneContainer('view');

            new Ajax.Updater
                ('MessagePane', target,
                 {asynchronous:true, 
                  evalScripts:true, 
                  onSuccess:function(request, json){ NewsReaderApp.mode = 'posting' },
                  onComplete:function(request, json){hideLoading()}, 
                  onLoading:function(request, json){showLoading()}
                 }
                );

        }
        else
          alert('未選擇新聞組。');
    },

    doNewPostSuccess : function()
    {
      alert('文章已成功發出。');  
      NewsReaderApp.mode = 'view';
      this.restoreMessagePaneContainer();
    },

	showSettingModal : function()
	{
		var target = '/frontend_dev.php/loadSettings';
		if (NewsReaderApp.mode != 'setting')
			NewsReaderApp.lastMode = NewsReaderApp.mode;

		addLog(target);

		new Ajax.Updater
			('SettingContainer', target,
			 {asynchronous:true, 
			  evalScripts:true, 
			  onSuccess:function(request, json){
					$('SettingContainer').style.display = 'block';
					NewsReaderApp.mode = 'setting';
				},
			  onFailure:function(request, json){ alert('failed!') },
			  onComplete:function(request, json){
						hideLoading();
						var e = $('SettingNameField');
						if (e)
						{
							e.focus();
							e.select();
						}
					}, 
			  onLoading:function(request, json){showLoading()}
			 }
			);
	},
	
	updateSettingSuccess: function()
	{
		$('SettingContainer').style.display = 'none';
		NewsReaderApp.mode = NewsReaderApp.lastMode;
	},
	
	closeSettingModal : function()
	{
		$('SettingContainer').style.display = 'none';
		NewsReaderApp.mode = NewsReaderApp.lastMode;
		return false;
	}

 }

 window.onload = function ()
 {
    addLog('Document loaded.');
    NewsReaderApp.start();
 }

 window.onresize = function()
 {
    addLog('Resized!');
    NewsReaderApp.resizeControls();
 }

 function showLoading()
 {
   Element.show('LoadingIcon');
 }

 function hideLoading()
 {
   Element.hide('LoadingIcon');
 }
