/**************************************

  deskDo -- todolist on your desktop

  (c) 2005 Pixel-Apes.

 **************************************/


function deskDoWrapper( idHook, leftPx, topPx, widthPx ) 
{ 
  this.bindSelf();

  if (idHook != false) 
    this.hook = document.getElementById( idHook );
  else
    this.hook = this.constructHook();

  /*
  for now dont work in MSIE
  if (topPx != false)   this.hook.style.top   = topPx   + "px";
  if (leftPx != false)  this.hook.style.left  = leftPx  + "px";
  if (widthPx != false) this.hook.style.width = widthPx + "px";
  */

  this.buildWrapper();
  this.buildDesk();

  this.server  = new deskDoServer ( this.desk );
  this.storage = new deskDoStorage( this.desk, this.server );

  this.desk.startup();
  this.server.doCheckAuth();
}

deskDoWrapper.prototype = 
{
    auth : false,
    user : {},

    hook : false,
    desk : false,

    defaultText : "", 
    
    // static stuff
    prefix : "deskDoWrapper",
    all : [],
    bindSelf : function()
    {
      deskDoWrapper.prototype.all[ deskDoWrapper.prototype.all.length ] = this;
      this.id = deskDoWrapper.prototype.prefix + deskDoWrapper.prototype.all.length;
    },
    onSurfaceClick : function()
    {
      for(var i in this.all)
      {
        this.all[i].onHideLoginFacility();

        if (this.all[i].desk)
          this.all[i].desk.onSurfaceClick();
      }

      //
      if (this._surfaceClickReturnFalse) 
      { 
        return this._surfaceClickReturnFalse=false;
      }
    },


    constructHook : function()
    {
      var hook = document.createElement("div");
      document.body.appendChild( hook );
      hook.style.position = "absolute";
      hook.style.left = "0";
      hook.style.top  = "0";
      hook.style.width = "100%";
      return hook;
    },

    buildWrapper : function()
    {
      var html = '<div id="'+this.id+'" class="desk-do">'+
                  '<div class="title-">'+
                   '<div id="'+this.id+'_auth" class="login- guest-">'+
                     '<a id="'+this.id+'_login" onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onLoginClick();return false" href="javascript:;">Log in...</a>'+
                     '<div onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onLoginFormClick();return true" '+
                                 ' id="'+this.id+'_loginform"></div>'+
                   '</div>'+
                   '<div id="'+this.id+'_desklist" class="desklist-"></div>'+
                   '<div class="more-options-">'+
                    '<small><span id="'+this.id+'_patch_no"></span></small>&nbsp;'+
                    '&lsaquo;&lsaquo;&nbsp;'+
                    '<a href="javascript:;" onclick="document.getElementById(\''+this.id+'\')._desk.onUndo(); return false;" '+
                    '   title="Undo one step" class="redo-">undo</a>'+
                    '&nbsp;&nbsp;&nbsp;'+
                    '<a href="javascript:;" onclick="document.getElementById(\''+this.id+'\')._desk.onRemoveAllCompleted(); return false;" title="Remove all tasks marked as completed" class="remove-all-completed-">cleanup</a>'+
                   '</div>'+
                   
                   '<span id="'+this.id+'_edit_cancel_block">'+
                     '<input type="button" id="'+this.id+'_edit_btn" class="edit-btn-" value="(temp)" '+
                            'onclick="if (document.getElementById(\''+this.id+'\')._desk.editAllMode) '+
                                         ' document.getElementById(\''+this.id+'\')._desk.doSaveAll(); '+
                                     'else document.getElementById(\''+this.id+'\')._desk.doEditAll(); '+
                                     'document.getElementById(\''+this.id+'\')._desk.skipNextOnClick(); return false" /> '+
                     '&nbsp;&nbsp;&nbsp;'+
                     '<a href="javascript:;" style="display:none" id="'+this.id+'_cancel_btn" '+
                        'onclick="if (document.getElementById(\''+this.id+'\')._desk.editAllMode) document.getElementById(\''+this.id+'\')._desk.doCancelAll(); '+
                                 'document.getElementById(\''+this.id+'\')._desk.skipNextOnClick(); '+
                                 'return false;">cancel</a>'+
                    '</span>'+
                  '</div>'+
                  '<div id="'+this.id+'_conflict" style="display:none"></div>'+
                  '<div id="'+this.id+'_wrapper" class="body-"></div>'+
                  '<div id="'+this.id+'_edit" style="display:none"><div></div></div>'+
                 '</div>';

      this.hook.innerHTML = html;
      this.wrapper = document.getElementById( this.id );
    },

    buildDesk : function()
    {
      this.desk = new deskDo( this.id+ "_wrapper", this.id+ "_edit", this.id+ "_edit_btn", this.id+ "_cancel_btn", 
                              this.defaultText );
      this.desk.wrapper = this;
      this.wrapper._desk = this.desk;
    },

    updatePatchNo : function( newPatchNo )
    {
      var pn = document.getElementById( this.id+"_patch_no" );
      pn.innerHTML = newPatchNo;
    },

    // switch desk facility
    showSwitchDeskFacility : function()
    {
      if (this.user.desks.length < 2) return this.hideSwitchDeskFacility();

      var options = "";
      for( var i in this.user.desks )
      {
        var tag = this.user.desks[i].tag;
        if (tag == "") tag = "(default)";
        
        var selected="";
        if (this.user.desks[i].supertag == this.desk.storage.tag) selected = 'selected="selected"';
        
        options += '<option value="'+ this.user.desks[i].supertag +'" '+selected+'>'+tag+'</option>';
      }
      var container = document.getElementById( this.id + "_desklist" );
      container.style.display  = "block";
      container.innerHTML = '<select onchange="document.getElementById(\''+this.id+'\')._desk.wrapper.onSwitchDesk(this.value);">'+
                            options+
                            '</select>';
    },
    hideSwitchDeskFacility : function()
    {
      // clean custom desks from flash
      for( var i in this.user.desks )
        if (this.user.desks[i].supertag != "")
          this.desk.storage.cleanDesk( this.user.desks[i].supertag );

      this.desk.storage.switchTo( "" );

      var container = document.getElementById( this.id + "_desklist" );
      container.innerHTML = "";
      container.style.display  = "none";
    },
    onSwitchDesk : function( newTag )
    {
      if (!this.isConflict) this.desk.save();

      this.storage.switchTo( newTag );
      this.showSwitchDeskFacility();
    },

    // login facility
    showLoginFacility : function()
    {
      var container = document.getElementById( this.id + "_loginform" );
      container.style.display  = "block";
      this._loginFacilityShown = true;
    },
    hideLoginFacility : function()
    {
      var container = document.getElementById( this.id + "_loginform" );
      container.style.display  = "none";
      this._loginFacilityShown = false;
    },
    buildLoginForm : function()
    {
      var container = document.getElementById( this.id + "_loginform" );
      container.innerHTML = 
       '<div id="'+this.id+'_login_form"  class="loginform- guest-">'+
       '<div id="'+this.id+'_login_table">'+
       '<strong id="'+this.id+'_login_table_head">Enter login and password</strong>'+
        '<div class="loginformbody-">'+
       '<label>Login:</label><input type="text"     id="'+this.id+'_login_field_login" class="loginfield-" />'+
       '<label>Password:</label><input type="password" id="'+this.id+'_login_field_password" class="loginfield-" />'+
       '<input type="submit" id="'+this.id+'_login_field_submit" '+
                      ' onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onLoginSubmit();return false" class="loginsend-" value="Log In" />'+
                      '<a target="_blank" href="http://deskdo.yandex-nano.ru/registration">register an account</a>'+
       '</div></div></div>';

      this.showLoginFacility();
      var login   = document.getElementById( this.id+"_login_field_login" );
      login.focus();
      login.focus();
    },
    buildUserInfo : function()
    {
      var container = document.getElementById( this.id + "_loginform" );
      container.innerHTML = 
       '<div class="auth-panel- auth-">'+
       '<input type="submit" '+
             ' onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onLogout();return false" value="Log Out" />'+
       '</div>';
      this.showLoginFacility();
    },

    // conflictFacility
    isConflict : false,
    _conflict  : { "client" : "", "server" : "" },
    buildConflictFacility : function()
    {
      var container = document.getElementById( this.id + "_conflict" );
      container.innerHTML = 
       '<div class="conflict-panel-" id="'+this.id+'_conflict_panel">'+
         '<input type="button"  class="conflict-btn-"'+
               ' onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onConflictResolve();return false" value="Use this version" />'+
         '<div id="'+this.id+'_conflict_server" class="pane-">'+
           '<a class="undo-" title="Step back in server history" href="javascript:;" onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onConflictUndo();return false;">&lsaquo;&lsaquo;&lsaquo;</a>'+
           '&nbsp;&nbsp;'+
           '<a href="javascript:;" onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onConflictSwitch(\'server\');return false;">server</a>'+
           '&nbsp;&nbsp;'+
           '<a class="redo-" title="Step forward in server history" href="javascript:;" onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onConflictRedo(\'server\');return false;">&rsaquo;&rsaquo;&rsaquo;</a>'+
         '</div>'+                    
         '<div id="'+this.id+'_conflict_client" class="pane- current-">'+
           '<a href="javascript:;" onclick="document.getElementById(\''+this.id+'\')._desk.wrapper.onConflictSwitch(\'client\');return false;">client</a>'+
         '</div>'+
         '<div class="pane-">Version conflict!</div>'+
       '<br clear="all" /></div>';
      this._ConflictUndoRedoColors( true );

    },
    hideConflictFacility : function()
    {
      this.isConflict = false;
      var container = document.getElementById( this.id + "_conflict" );
      container.style.display  = "none";

      this.showEditAllFacility();
    },
    showConflictFacility : function()
    {
      this.isConflict = true;
      var container = document.getElementById( this.id + "_conflict" );
      if (container.innerHTML == "") this.buildConflictFacility();
      container.style.display  = "block";

      this.hideEditAllFacility();
    },

    showEditAllFacility : function()
    {
      var edit_cancel_block   = document.getElementById( this.id + "_edit_cancel_block" );
      edit_cancel_block.style.visibility  = "visible";
    },
    hideEditAllFacility : function()
    {
      var edit_cancel_block   = document.getElementById( this.id + "_edit_cancel_block" );
      edit_cancel_block.style.visibility  = "hidden";
    },



    // event handlers
    onConflict : function( clientData, serverData )
    {
      this._conflict = {
              "client" : clientData,
              "server" : serverData
                       }
      this.showConflictFacility();
      this.onConflictSwitch( "server" );
    },
    onConflictSwitch : function( to )
    {
      // conflict bar switch
      var panes = { "client" : document.getElementById( this.id+"_conflict_client" ),
                    "server" : document.getElementById( this.id+"_conflict_server" )
                  };
      for(var i in panes)
        if (i == to) panes[i].className = "pane- current-";
        else         panes[i].className = "pane-";

      // editable switch
      this.desk.buildFromScratch( this._conflict[ to ] );
      this.desk.doInitView();
      this.desk.doViewAll();
      this.desk.setReadonly(true);
    },
    onConflictResolve : function()
    {
      this.desk.save();
      this.desk.setReadonly(false);
      this.hideConflictFacility();
    },
    _ConflictUndoRedoColors : function( isUndo )
    {
      var haveUndo = true;
      var haveRedo = true;
      if (this.desk.storage.version == 1) haveUndo=false;
      if (this.desk.storage.maxVersion == this.desk.storage.version) haveRedo=false;
      if (isUndo)
        if (this.desk.storage.version == 2) haveUndo=false; 
        else
          if (this.desk.storage.maxVersion == this.desk.storage.version) haveRedo=true;
          else;
      else
        if (this.desk.storage.maxVersion == this.desk.storage.version+1) haveRedo=false;
        else
          if (this.desk.storage.version == 1) haveUndo=true;
          else;

      var pane = document.getElementById( this.id+"_conflict_panel" );
      if (!pane) return;
      pane.className = "conflict-panel- "+(haveUndo?"":" no-undo- ")+(haveRedo?"":" no-redo- ");
    },
    onConflictUndo : function()
    {
      this._ConflictUndoRedoColors( true );
      this.desk.onUndo();
    },
    onConflictRedo : function()
    {
      this._ConflictUndoRedoColors( false );
      this.desk.onRedo();
    },
    onHideLoginFacility : function()
    {
      if (!this._dontHideLoginFacility) this.hideLoginFacility();
      this._dontHideLoginFacility = false;
    },
    onLoginFormClick : function()
    {
      this._dontHideLoginFacility = true;
    },
    onLoginClick : function()
    {
      if (!this._loginFacilityShown) this._dontHideLoginFacility = true;
      if (!this.auth) this.buildLoginForm();
      else            this.buildUserInfo();
    },
    onLogout : function()
    {
      this.hideSwitchDeskFacility();

      this.auth = false;
      this.user = {};

      this.hideLoginFacility();
      this.hideConflictFacility();

      var auth    = document.getElementById( this.id+"_auth" );
      var login   = document.getElementById( this.id+"_login" );
      auth.className = "login- guest-";
      login.innerHTML = "Login...";

      this.server.doLogout();

      // reset clientside storage & desk
      this.storage.reset();
      this.desk.buildFromScratch( this.defaultText );
      this.desk.doInitView();
      this.desk.doViewAll();
      this.desk.save();
    },
    onLoginSubmit : function()
    {
      var login  = document.getElementById( this.id+"_login_field_login" );
      var pwd    = document.getElementById( this.id+"_login_field_password" );
      var submit = document.getElementById( this.id+"_login_field_submit" );
      var table  = document.getElementById( this.id+"_login_table" );
      var head   = document.getElementById( this.id+"_login_table_head" );
      var auth   = document.getElementById( this.id+"_auth" );
      var form   = document.getElementById( this.id+"_login_form" );

      login.disabled  = true;
      pwd.disabled    = true;
      submit.disabled = true;
      table.className = "wait-";
      form.className = "loginform- logging-";
      auth.className = "login- logging-";
      head.innerHTML = "Logging in, please wait...";

      this.server.doLogin( login.value, pwd.value );
    },
    onLoginCancel : function()
    {
      var login  = document.getElementById( this.id+"_login_field_login" );
      var pwd    = document.getElementById( this.id+"_login_field_password" );
      var submit = document.getElementById( this.id+"_login_field_submit" );
      var table  = document.getElementById( this.id+"_login_table" );
      var head   = document.getElementById( this.id+"_login_table_head" );
      var auth   = document.getElementById( this.id+"_auth" );
      var form   = document.getElementById( this.id+"_login_form" );

      if (!table) return;

      table.className = "error-";
      auth.className = "login- guest-";
      form.className = "loginform- guest-";
      head.innerHTML = "Login failed, try again";
      login.disabled  = false;
      pwd.disabled    = false;
      submit.disabled = false;
      pwd.value = "";

    },
    onLoginComplete : function( user )
    {
      var auth    = document.getElementById( this.id+"_auth" );
      var login   = document.getElementById( this.id+"_login" );

      this.user = user;
      this.auth = true;

      this.hideLoginFacility();
      auth.className = "login- auth-";
      login.innerHTML = "As: " + user.login;

      if (user.isMultidesk) this.showSwitchDeskFacility();
      else                  this.hideSwitchDeskFacility();

      var switched = false;
      if (location.search != "")
      {
        for( var i in this.user.desks )
          if ("?" + this.user.desks[i].tag == location.search)
          {
            switched = true;
            this.storage.switchTo( this.user.desks[i].tag );
            this.showSwitchDeskFacility();
          }
      }
      // start loading
      if (!switched) this.storage.load();
    },




    // simple function to end the class definition.
    undef : function( param ) { return param; }
}




