if (window['console'] === undefined) {
  window.console = {
    log: Prototype.emptyFunction
  };
};

var Scraplr = {};

Scraplr.TaskBins = {
  strActiveTaskBin : 'tasksBin',
  strActiveTaskBinId : '1',
  switchActiveTaskBinTab: function (selectedTaskTab){
    
    var strUserId = Scraplr.Utilities.getUserId();
    var strCurrentTaskTab = selectedTaskTab.identify();
    Scraplr.TaskBins.strActiveTaskBin = strCurrentTaskTab;
    
    if(strCurrentTaskTab != 'tasksBin'){
      if(Scraplr.Hud.boolRouterHudIsVisible){
        Scraplr.Hud.objRouterHud.close();
      }
    }
    
    $('searchKeyword').value = '';
        
    switch(strCurrentTaskTab){
      case 'tasksBin':
        strActiveBinId = '1';                             
        Scraplr.TaskBins.strActiveTaskBinId = strActiveBinId;
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').show();
        $('cmdAddTaskSubtitle').innerHTML = 'Add new task to Task Bin';
        $('cmdTaskAdd').show();
        $('cmdTaskComplete').show();
        $('cmdTaskLog').show();
        $('cmdTaskPublish').show();
        $('cmdRemoveTaskTitle').innerHTML = "Remove task";
        $('cmdRemoveTaskSubtitle').innerHTML = "Move selected task item to task recycler";        
      break;
      case 'nextBin':
        strActiveBinId = '2';
        Scraplr.TaskBins.strActiveTaskBinId = strActiveBinId; 
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').hide();
        $('cmdAddTaskSubtitle').innerHTML = 'Add new task to Next Bin';
        $('cmdTaskAdd').show();
        $('cmdTaskComplete').show();
        $('cmdTaskLog').show();
        $('cmdTaskPublish').show();
        $('cmdRemoveTaskTitle').innerHTML = "Remove task";
        $('cmdRemoveTaskSubtitle').innerHTML = "Move selected task item to task recycler";
      break;
      case 'scheduledBin':
        strActiveBinId = '3';                              
        Scraplr.TaskBins.strActiveTaskBinId = strActiveBinId;
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').hide();
        $('cmdAddTaskSubtitle').innerHTML = 'Add new task to Scheduled Bin';
        $('cmdTaskAdd').show();
        $('cmdTaskComplete').show();
        $('cmdTaskLog').show();
        $('cmdTaskPublish').show();
        $('cmdRemoveTaskTitle').innerHTML = "Remove task";
        $('cmdRemoveTaskSubtitle').innerHTML = "Move selected task item to task recycler";
      break;
      case 'projectBin':
        strActiveBinId = '4';                              
        Scraplr.TaskBins.strActiveTaskBinId = strActiveBinId;
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').hide();
        $('cmdTaskAdd').hide();
        $('cmdTaskComplete').hide();
        $('cmdTaskLog').hide();
        $('cmdTaskPublish').hide();
        $('cmdRemoveTaskTitle').innerHTML = "Remove task";
        $('cmdRemoveTaskSubtitle').innerHTML = "Move selected task item to task recycler";
      break;
      case 'laterBin':
        strActiveBinId = '5';                              
        Scraplr.TaskBins.strActiveTaskBinId = strActiveBinId;
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').hide();
        $('cmdAddTaskSubtitle').innerHTML = 'Add new task to Later Bin';
        $('cmdTaskAdd').show();
        $('cmdTaskComplete').show();
        $('cmdTaskLog').show();
        $('cmdTaskPublish').show();
        $('cmdRemoveTaskTitle').innerHTML = "Remove task";
        $('cmdRemoveTaskSubtitle').innerHTML = "Move selected task item to task recycler";
      break;
      case 'completedBin':
        strActiveBinId = '6'; 
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').hide();
        $('cmdTaskAdd').hide();
        $('cmdTaskComplete').hide();
        $('cmdTaskLog').hide();
        $('cmdTaskPublish').hide();
        $('cmdRemoveTaskTitle').innerHTML = "Remove task";
        $('cmdRemoveTaskSubtitle').innerHTML = "Move selected task item to task recycler";
      break;
      case 'recycleBin':
        strActiveBinId = '7';                              
        Scraplr.TaskBins.strActiveTaskBinId = strActiveBinId;
        Scraplr.TaskPaper.loadTaskPaper(strUserId, strActiveBinId);
        $('btHudTaskFlow').hide();
        $('cmdRemoveTaskTitle').innerHTML = "Empty Task Recycler";
        $('cmdRemoveTaskSubtitle').innerHTML = "Completely remove task(s) inside task recycler";
        $('cmdTaskAdd').hide();
        $('cmdTaskComplete').hide();
        $('cmdTaskLog').hide();
        $('cmdTaskPublish').hide();
      break;                                    
    }
    if (Scraplr.TaskBins.strActiveTaskBinId === '4'){
      $('cmdTaskAdd').addClassName('hidden');
      $('cmdProjectAdd').removeClassName('hidden');      
    }else{
      $('cmdTaskAdd').removeClassName('hidden');
      $('cmdProjectAdd').addClassName('hidden');
    }

    $$('div.taskBinTabItem').each(function(obj){
      if(obj.hasClassName('taskBinTabAux')){
        obj.removeClassName('tabAuxActive');
      }else{
        obj.removeClassName('tabActive');
      }           
    });
      
    if(selectedTaskTab.hasClassName('taskBinTabAux')){
      selectedTaskTab.addClassName('tabAuxActive');
    }else{
      selectedTaskTab.addClassName('tabActive');
    }
    
    $$('div.taskBinIco').each(function(obj){
      obj.removeClassName('taskBinIcoActive');           
    });  
    selectedTaskTab.down('div.taskBinIco').addClassName('taskBinIcoActive');
    
    $$('div.taskBinLabel').each(function(obj){
      obj.removeClassName('labelActive');           
    });
    if(!selectedTaskTab.hasClassName('taskBinTabAux')){
      selectedTaskTab.down('div.taskBinLabel').addClassName('labelActive');
    } 
    
    $$('div.tasksBinNumBadge').each(function(obj){
      obj.removeClassName('badgeActive');           
    }); 
    
    if(!selectedTaskTab.hasClassName('taskBinTabAux')){    
      selectedTaskTab.down('div.tasksBinNumBadge').addClassName('badgeActive');
    }
    
    $$('div.taskBinBadge').each(function(obj){
      obj.removeClassName('taskBinBadgeTabActive');           
    });    
    selectedTaskTab.down('div.taskBinBadge').addClassName('taskBinBadgeTabActive');    

  
  },
  initTaskTabs: function (){
    $('tasksBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('tasksBin'));	
    // end observe click
    });

    $('nextBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('nextBin'));	
    // end observe click
    });

    $('scheduledBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('scheduledBin'));	
    // end observe click
    });

    $('projectBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('projectBin'));	
    // end observe click
    });        

    $('laterBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('laterBin'));	
    // end observe click
    });

    $('completedBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('completedBin'));	
    // end observe click
    });

    $('recycleBin').observe('click',function(event){
      Scraplr.TaskBins.switchActiveTaskBinTab($('recycleBin'));	
    // end observe click
    });
    
  }
};
  
Scraplr.TagsBar = {
  
};            

Scraplr.MainCommands = {
  initCommandButton: function (){
    $('cmdTaskAdd').observe('click',function(event){
      Scraplr.UI.openNewEntryDialog();
    }); 
    $('cmdProjectAdd').observe('click',function(event){	
    // end observe click
    });
    $('cmdTaskComplete').observe('click',function(event){	
      var intSelectedTasks = Scraplr.UI.arrSelectedTask.size();
      var arrSelectedTask = Scraplr.UI.arrSelectedTask; 
      if(intSelectedTasks>=1){
        for (i=0; i<intSelectedTasks; i++) {
          var objTarget = arrSelectedTask[i].down('div.taskItemCheck');
          //Scraplr.TaskPaper.toggleChecked(arrSelectedTask[i]); 
          if(objTarget.hasClassName('itemUnchecked')){
            objTarget.removeClassName('itemUnchecked');
            objTarget.addClassName('itemChecked');
            objTarget.up('div.taskItem').addClassName('completed');
            Scraplr.TaskPaper.processTask('complete', arrSelectedTask[i].identify(), null);      
          }
        }
        Scraplr.TaskPaper.clearSelectedTask();
      }else{
        Scraplr.UI.showDialog ('alert', 'You have to select at least one task to be marked as completed','',function (){
           
        }, function (){
           
        },false);
      }
    // end observe click
    });
         
    $('cmdTaskRemove').observe('click',function(event){	
      var intSelectedTasks = Scraplr.UI.arrSelectedTask.length;
      var arrSelectedTask = Scraplr.UI.arrSelectedTask;   
      if(Scraplr.TaskBins.strActiveTaskBinId != '7'){
        if(intSelectedTasks>=1){ 
             Scraplr.TaskPaper.processTask('remove', null, null);  
        }else if(intSelectedTasks<1){
          Scraplr.UI.showDialog ('alert', 'You have to select at least one task to remove.', '',function (){}, function (){},true);
        }
      } else if(Scraplr.TaskBins.strActiveTaskBinId == '7'){
        Scraplr.UI.showDialog ('confirm', 'Are you sure want to empty task recycler? <br/>', 'All tasks inside task recycler will be removed.<br/>You can not undo this action.',function (){
           
        }, function (){
        Scraplr.TaskPaper.processTask('empty', null, '7');   
           
        },false);
      }
    // end observe click
    });
    $('cmdTaskLog').observe('click',function(event){	
      var intSelectedTasks = Scraplr.UI.arrSelectedTask.size();
      var arrSelectedTask = Scraplr.UI.arrSelectedTask;
      var arrSelectedTaskIds = []; 
      if(intSelectedTasks>=1){              
        var strTaskCaptions = Scraplr.Utilities.getSelectedTaskName();
        Scraplr.UI.showDialog ('confirm', 'Move following tasks to log ?', strTaskCaptions,function (){
          //Scraplr.TaskPaper.clearSelectedTask();
        }, function (){  
           Scraplr.TaskPaper.processTask('log', null, null);
        },false);
      }else{
        Scraplr.UI.showDialog ('alert', 'You have to select at least one task to log.','',function (){}, function (){},false);
      }
    // end observe click
    });
    $('cmdTaskPublish').observe('click',function(event){	
      var intSelectedTasks = Scraplr.UI.arrSelectedTask.size();
      var arrSelectedTask = Scraplr.UI.arrSelectedTask;
      var arrSelectedTaskIds = []; 
      if(intSelectedTasks>=1){              
        var strTaskCaptions = Scraplr.Utilities.getSelectedTaskName();
        Scraplr.UI.showDialog ('confirm', 'Put following tasks to your public page?', strTaskCaptions,function (){
          Scraplr.TaskPaper.clearSelectedTask();
        }, function (){  
           Scraplr.TaskPaper.processTask('publish', null, null);
        },false);
      }else{
        Scraplr.UI.showDialog ('alert', 'You have to select at least one task to publish.','',function (){}, function (){},false);
      }
    // end observe click
    });
    $('cmdTaskViewPublic').observe('click',function(event){	
       var strUserName = Scraplr.Utilities.getUserName();
      Scraplr.Utilities.redirect('/'+strUserName+'/public/');
    // end observe click
    });
  }
};                  

Scraplr.TaskPaper = {
  boolIsEditingTaskTitle : false,
  arrTaskOrder:[],
  arrActiveTitleInPlaceEditor:[],
  arrActivatedTitleInPlaceEditors:[],
  loadTaskPaper: function (strUserId, strTaskBinId){ 
    var strUserId = Scraplr.Utilities.getUserId();
    var url = '';
    if(strTaskBinId == '4'){
      url = '/'+Scraplr.Utilities.getUserName()+'/response/task_project/4/'; 
      Scraplr.Utilities.caramelizeScrap(url, false, false, null, function (){
        $('taskPaperWrapper').childElements().invoke('hide');
        Element.show('activityIndicator');        
      },function(){
        Element.hide('activityIndicator'); 
        
        var strHtmlSource = Scraplr.Utilities.objCaramelizedHtml;
        
        if(strHtmlSource.startsWith('<div id="taskItem')){ 
          if(!$('noTask').hasClassName('hidden')){
            $('noTask').addClassName('hidden');
          }
        
          $('taskPaperWrapper').update(Scraplr.Utilities.objCaramelizedHtml);        
          Scraplr.UI.initSortableTaskItems();
          Scraplr.UI.initTaskItemDraggable(); 
          Scraplr.UI.initTaskPaperFoldHandler();
          Scraplr.UI.initTaskCheckedToggler();
          
          if (Scraplr.Prefs.boolShowTips){
            Scraplr.UI.initToolTips();
          }   
            
          $$('div.taskItemSelectIndy').invoke('hide');
          $$('div.taskItemDetailWrapper').invoke('hide'); 
          
          $$('div.projectItemWrapper').each(function(obj){
            obj.observe('click',function(event){ 
               $$('div.projectItemWrapper').each(function(obj2){
                 obj2.removeClassName('projectWrapperActive');           
               });    
               obj.addClassName('projectWrapperActive');
            // end observe click
            });           
          });
          Scraplr.TaskPaper.loadTaskTags(strUserId, strTaskBinId);
          Scraplr.TaskPaper.countTaskItem(); 
          Scraplr.UI.initTaskBinNumBadge();
          $('projectBinNumBadge').removeClassName('hidden');
        }else{
          $('taskTagsWrapper').hide();
          $('tagsTokenList').innerHTML = '';
          $('noTask').removeClassName('hidden');
          $('noTaskTitle').update('No Project here yet');
          $('noTaskNote').update('Project container will be available in the upcoming Beta release');
          $('taskPaperWrapper').update('');
          Scraplr.TaskPaper.countTaskItem();
          Scraplr.UI.initTaskBinNumBadge();
        }
         
      });      
    }else if(strTaskBinId != '4'){       
      url = '/'+Scraplr.Utilities.getUserName()+'/response/task_bin/'+strTaskBinId;
      Scraplr.Utilities.caramelizeScrap(url, false, false, null, function (){
        $('taskPaperWrapper').childElements().invoke('hide');
        Element.show('activityIndicator');
      },function(){
        Element.hide('activityIndicator');
        var strHtmlSource = Scraplr.Utilities.objCaramelizedHtml;
        
        if(strHtmlSource.startsWith('<div id="taskItem')){ 
          if(!$('noTask').hasClassName('hidden')){
            $('noTask').addClassName('hidden');
          }
          $('taskPaperWrapper').update(strHtmlSource);        
          Scraplr.UI.initSortableTaskItems();
          Scraplr.UI.initTaskItemDraggable(); 
          Scraplr.UI.initTaskPaperFoldHandler();
          Scraplr.UI.initTaskCheckedToggler();
          Scraplr.UI.initTaskPaperTitleEdit(); 
          if (Scraplr.Prefs.boolShowTips){
            Scraplr.UI.initToolTips();
          }    
          $$('div.taskItemSelectIndy').invoke('hide');
          $$('div.taskItemDetailWrapper').invoke('hide');
          Scraplr.TaskPaper.loadTaskTags(strUserId, strTaskBinId);
          Scraplr.TaskPaper.countTaskItem();
          
          $$('div.taskItem').each(function(obj){
            var strTargetIds = obj.identify().gsub('taskItem','');
            Scraplr.TaskPaper.checkDue(strTargetIds);           
          });
          
          Scraplr.UI.initTaskBinNumBadge();          
        }else {  
          $('taskTagsWrapper').hide();
          $('tagsTokenList').innerHTML = '';
          $('noTask').removeClassName('hidden');
          $('taskPaperWrapper').update('');          
          console.log('strTaskBinId:'+strTaskBinId);
          switch(strTaskBinId){
            case '1':
              $('noTaskTitle').update('No task todo here yet');
              $('noTaskNote').update('Click "Add Task" button to create one');
            break;
            case '2':
              $('noTaskTitle').update('No task todo here yet');
              $('noTaskNote').update('Click "Add Task" button to create one');
            break; 
            case '3':
              $('noTaskTitle').update('No scheduled task todo here yet');
              $('noTaskNote').update('Click "Add Task" button to create one');
            break; 
            case '5':
              $('noTaskTitle').update('No task todo here yet');
              $('noTaskNote').update('Click "Add Task" button to create one');
            break; 
            case '6':
              $('noTaskTitle').update('No task logged as completed here yet');
              $('noTaskNote').update('');
            break; 
            case '7':
              $('noTaskTitle').update('No task to recycle here yet');
              $('noTaskNote').update('');
            break;
          }
          Scraplr.TaskPaper.countTaskItem(); 
          Scraplr.UI.initTaskBinNumBadge();         
        }      
      });
    }
    
        
  },
  loadTaskItemDetail: function (strObjId){
    //var intRandom = Scraplr.Utilities.randomize();    
    var strTargetIds = '';
    var arrTaskIds = strObjId.split("_"); 
    var strUserId = arrTaskIds[0];
    var strActiveBinId = arrTaskIds[1];
    var strTaskId = arrTaskIds[2];
    
    //var url = 'taskitemdetail.php?intRandom='+intRandom+'&strUserId='+strUserId+'&strActiveBinId='+strActiveBinId+'&strTaskId='+strTaskId;
    var url = '/'+Scraplr.Utilities.getUserName()+'/response/task_detail/'+strTaskId;  
    
    Scraplr.Utilities.caramelizeScrap(url, false, false, null, function (){
      $('taskItemBriefWrapper_'+strObjId).addClassName('taskItemIsLoading');
      $('taskItemBriefWrapper_'+strObjId).childElements().invoke('hide');    
    },function(){
       
      $('taskItemBriefWrapper_'+strObjId).removeClassName('taskItemIsLoading');    
      $('taskItem_'+strObjId).removeClassName('folded');
      $('taskItem_'+strObjId).addClassName('unfolded');  
      
      try{
        $$('div.ScraplrUI-widget-dropdown').invoke('hide');
      }catch(ex){}
      
      if($('taskItemTitle_'+strObjId+'-inplaceeditor')!=null){
        $('taskItemTitle_'+strObjId+'-inplaceeditor').show();
        $('taskItemTitle_'+strObjId).hide();
      }else{
        $('taskItemTitle_'+strObjId).show();
      }
      
      $('taskItemBriefWrapper_'+strObjId).hide();                            
      $('taskItemDetailWrapper_'+strObjId).update(Scraplr.Utilities.objCaramelizedHtml).show();      
      $('taskItemTitleLabel_'+strObjId).addClassName('hidden');
              
      strTargetIds = '_'+strObjId;     
            
      Scraplr.UI.initTaskPaperNoteEdit(strTargetIds);
      Scraplr.UI.initTaskItemTabs(strTargetIds);                
      Scraplr.UI.initDueDatePicker(strTargetIds);
      Scraplr.UI.initReminderMeanPicker(strTargetIds);
      Scraplr.UI.initReminderMeanCheckList(strTargetIds); 
      Scraplr.UI.initTaskItemShareMeanPicker(strTargetIds);
      Scraplr.UI.initTaksItemShareMeanCheckList(strTargetIds);      
      Scraplr.UI.initTagsEntryBox(strTargetIds);
      Scraplr.TaskPaper.getTaskTags($('taskItemTags_'+strObjId));
      var arrThisCommentList = $('taskCommentList_'+strObjId).childElements();
      if(arrThisCommentList.length != 0){        
        var strLastCommentId = arrThisCommentList.last().identify();
        Scraplr.TaskComment.scrollToLatestComment($('taskComment_'+strObjId),$(strLastCommentId));
        
        //Scraplr.TaskComment.humanizeTaskCommentDate(arrThisCommentList);
      }
      Scraplr.TaskComment.countTaskComments(strObjId);
      Scraplr.TaskMate.countTaskMate(strObjId);
      arrTaskIds.clear();    
    });

  },
  loadTaskTags: function (strUserId, strTaskBinId){ 
    //collect unique tag(s) attached to user's task(s)
    var url = '/'+Scraplr.Utilities.getUserName()+'/response/task_tag_list/'+strTaskBinId;     
    Scraplr.Utilities.caramelizeScrap(url, false, false, null, function (){
    $('tagsBar').setStyle('width:200px;');
    $('tagsTokenList').innerHTML = '<li class="tagTokenCap"><span class="tagTokenSpan">Loading task tags...</span></li>';
    //create
    },function(){ 
      var strHtmlSource = Scraplr.Utilities.objCaramelizedHtml;
      if(strHtmlSource != '0'){      
        Scraplr.Utilities.initQuicksilverSearch('searchKeyword', 'div.taskItem');
        $('tagsTokenList').innerHTML = strHtmlSource;
        Scraplr.UI.setTagBar();              
      }else{
        $('taskTagsWrapper').hide();
      }
    });

  },
  getTaskTags: function (objTagBar){           
    try{
      var strTagBarId = objTagBar.identify();
      var strIds = objTagBar.identify().gsub('taskItemTags_','');
      var strTagsSource = $('taskItemTagsString_'+strIds).value;
      if(strTagsSource!='0'){        
        var arrTaskTags = strTagsSource.split(';');       
        var intTagsCount = arrTaskTags.length;
        if (intTagsCount > 0){
          objTagBar.down('div.taskTagLoading').hide();
          for (i=0; i<intTagsCount; i++) {  
            var strTaskTag = arrTaskTags[i];
            Scraplr.TaskPaper.createUnexistTagToken(strTagBarId.gsub('taskItemTags_','holdertagListBox_'),strTaskTag);
          }
        }else{
          objTagBar.down('div.taskTagLoading').hide();
        }
      }
    }catch(ex){
      console.log(ex);
    }finally{
      objTagBar.down('div.taskTagLoading').hide();
    }    
  },
  toggleChecked: function (objTaskItem, event){
    try{
      event.stop(); // stop the event, otherwise event will bubble and continue selecting the task item
    }
    catch(ex){}
    if(objTaskItem.hasClassName('itemUnchecked')){
      objTaskItem.removeClassName('itemUnchecked');
      objTaskItem.addClassName('itemChecked');
      objTaskItem.up('.taskItem').addClassName('completed');      
      Scraplr.TaskPaper.submitTaskCheck('true',objTaskItem.identify());
    }else if(objTaskItem.hasClassName('itemChecked')){
        objTaskItem.removeClassName('itemChecked');
        objTaskItem.addClassName('itemUnchecked');
        objTaskItem.up('.taskItem').removeClassName('completed');        
        Scraplr.TaskPaper.submitTaskCheck('false',objTaskItem.identify());
    }
  },
  toggleFold: function (objTaskItem){
    var strObjId =  objTaskItem.identify().gsub('taskItem_','');
    var boolTaskIsCompleted = $('taskItemCheck_'+strObjId).hasClassName('itemChecked');
    if(objTaskItem.hasClassName('unfolded')){ 
      try{
        $$('div.ScraplrUI-widget-dropdown').invoke('hide');  
      }catch(ex){
       //
      } 
      
      try{
        $('taskItemTitle_'+strObjId+'-inplaceeditor').hide();
      }catch(ex){
        //
      }finally{
        $('taskItemDetailWrapper_'+strObjId).hide();
        $('taskItemDetailWrapper_'+strObjId).update('');
        $('taskItemBriefWrapper_'+strObjId).childElements().invoke('show');
        $('taskItemBriefWrapper_'+strObjId).show(); 
        $('taskItemTitle_'+strObjId).hide();
        $('taskItemTitleLabel_'+strObjId).update($('taskItemTitle_'+strObjId).innerHTML);
        $('taskItemTitleLabel_'+strObjId).removeClassName('hidden'); 
        objTaskItem.removeClassName('unfolded');
        objTaskItem.addClassName('folded');       
      } 
      
    }else if(objTaskItem.hasClassName('folded')){
        $('taskItemSelect_'+strObjId).hide();
        $('taskItem_'+strObjId).down('div.taskItemTags').update('');         
        Scraplr.TaskPaper.loadTaskItemDetail(strObjId);       
    }    
  },
  toggleSelected: function (objTaskItem, event){
    var strObjId =  objTaskItem.identify().gsub('taskItem_','');    
    if(objTaskItem.hasClassName('itemSelected')){
      objTaskItem.removeClassName('itemSelected');
      $('taskItemSelect_'+strObjId).hide();
      Scraplr.UI.arrSelectedTask.pull(objTaskItem);      
    }else if(!objTaskItem.hasClassName('itemSelected')){
        objTaskItem.addClassName('itemSelected');
        $('taskItemSelect_'+strObjId).show();
        Scraplr.UI.arrSelectedTask.push(objTaskItem);        
    }   
    
    if (Scraplr.TaskBins.strActiveTaskBinId === '4'){      
      $$('div.projectItemWrapper').each(function(obj){
        obj.removeClassName('projectWrapperActive');           
      });
      var strParentProjectSectionId = objTaskItem.up('div.projectItemWrapper').identify();
      $(strParentProjectSectionId).addClassName('projectWrapperActive');    
    }
  },
  toggleEditTaskTitle: function (objTaskTitle){
      Scraplr.TaskPaper.boolIsEditingTaskTitle = true;
      objTaskTitle.toggle();
      objTaskTitle.next('input.taskItemTitleEditBox').toggle();
      objTaskTitle.next('input.taskItemTitleEditBox').value = objTaskTitle.innerHTML;  
      objTaskTitle.next('input.taskItemTitleEditBox').select();
  		var objTaskTitleHotKey = new HotKey('enter',function(event){
          if (Scraplr.TaskPaper.boolIsEditingTaskTitle) {
            objTaskTitle.next('input.taskItemTitleEditBox').toggle();
            objTaskTitle.innerHTML = objTaskTitle.next('input.taskItemTitleEditBox').value;
            objTaskTitle.toggle();
            Scraplr.TaskPaper.boolIsEditingTaskTitle = false;
  	      }
    	},{element:objTaskTitle.next('input.taskItemTitleEditBox').identify()});
  },
  createUnexistTagToken: function (objAutoCompleteInputText, strTokenText){
    var strTagsContainerId = objAutoCompleteInputText.gsub('holdertagListBox_','');
    if(!Scraplr.UI.boolNewEntryDialogIsVisible){
      var intExistingTagsCount = $('taskItemTags_'+strTagsContainerId).down('ul.pui-autocomplete-holder').childElements().size();
      var objExistingTokens = $('taskItemTags_'+strTagsContainerId).down('ul.pui-autocomplete-holder').childElements();
      objExistingTokens.each(function(obj){
        if(obj.hasClassName('pui-autocomplete-box')){
          var arrTokenContent = obj.down('span').innerHTML.split('<');
          var strTag = arrTokenContent[0];
        }                 
      });
    }else{
      var intExistingTagsCount = $('taskItemTagsNew').down('ul.new-entry-holder').childElements().size();
      var objExistingTokens = $('taskItemTagsNew').down('ul.new-entry-holder').childElements();
      objExistingTokens.each(function(obj){
        if(obj.hasClassName('new-entry-box')){
          var arrTokenContent = obj.down('span').innerHTML.split('<');
          var strTag = arrTokenContent[0];
        }                 
      });      
    }
    
    if (intExistingTagsCount < 6){
      if(!Scraplr.UI.boolNewEntryDialogIsVisible){
        var objAutoCompleteHolder = $(objAutoCompleteInputText).previous('ul.pui-autocomplete-holder'); // dummy check
        var element = Builder.node('li', {
          className:'pui-autocomplete-box',
          onclick:'Scraplr.Utilities.selectTaskTag(this)'
        },[
            Builder.node('span',strTokenText, Builder.node('a',{className:'closebutton', href:'#', onclick:'Scraplr.TaskPaper.removeTaskTag(this)'}))                  
          ]);
          element.writeAttribute("pui-autocomplete:value", strTokenText);
        $(objAutoCompleteInputText).previous('ul.pui-autocomplete-holder').down('li.pui-autocomplete-input').insert({ before: element });          
        Scraplr.TaskPaper.addTaskTag($(objAutoCompleteInputText).identify(), strTokenText); 
        var strUserId = Scraplr.Utilities.getUserId();
        var strTaskBinId = Scraplr.TaskBins.strActiveTaskBinId; 
        var strTagToAdd = $('taskItem_'+strTagsContainerId).down('div.taskItemTags').innerHTML;
        if (strTagToAdd =='0'){
          strTagToAdd = '';
        }else{
          strTagToAdd = strTagToAdd+';';
        }
        $('taskItem_'+strTagsContainerId).down('div.taskItemTags').update(strTagToAdd+strTokenText);
        Scraplr.TaskPaper.loadTaskTags(strUserId, strTaskBinId);
      }else{
        var element = Builder.node('li', {
          className:'new-entry-box',
          onclick:'Scraplr.Utilities.selectTaskTag(this)'
        },[
            Builder.node('span',strTokenText, Builder.node('a',{className:'closebutton', href:'#', onclick:'Scraplr.TaskPaper.removeTaskTag(this)'}))                  
          ]);
          element.writeAttribute("pui-autocomplete:value", strTokenText);
        $(objAutoCompleteInputText).previous('ul.new-entry-holder').down('li.new-entry-input').insert({ before: element });    
        Scraplr.TaskPaper.addTaskTag($(objAutoCompleteInputText).identify(), strTokenText);
      }
      
    } else{
      Scraplr.UI.showDialog ('alert', 'We think five tags for a task might be enough :)', 'Many tags for a task item would be confusing anyway..',function (){}, function (){},false);
    } 
  },
  toggleActiveProjectSection : function (){
    
  },
  clearSelectedTask: function (){
    var intSelectedTasks = Scraplr.UI.arrSelectedTask.size();
    var arrSelectedTask = Scraplr.UI.arrSelectedTask; 
    if(intSelectedTasks>1){
      try{
        for (i=0; i<intSelectedTasks; i++) {
          arrSelectedTask[i].removeClassName('itemSelected');
          arrSelectedTask[i].down('div.taskItemSelectIndy').hide();
        }
      }catch(ex){
        // task item might has been removed from DOM..
      }
    }
    Scraplr.UI.arrSelectedTask.clear();
    $$('div.taskItemSelectIndy').invoke('hide');    
  },
  submitTaskCheck: function (boolTaskIsDone, strTaskCheckSourceId){
    Scraplr.TaskPaper.processTask('complete', strTaskCheckSourceId, null);
  },
  processTask: function (strAct, strTaskSourceId, strTargetTaskBinId){
    
    var strUrl = ''; 
    var arrTaskIdsToProcess =[];     
    var strIdsToProcess ='';
    var strTaskIdToProcess = '';

    switch(strAct){
      case 'complete':
        strUrlAct = 'complete_task';
      break;
      case 'remove': 
        strUrlAct = 'remove_task';
      break;
      case 'log':
        strUrlAct = 'log_task';
      break;
      case 'publish':
        strUrlAct = 'publish_task';
      break;
      case 'move':
        strUrlAct = 'move_task';
      break;
      case 'empty':
        strUrlAct = 'empty_task';
      break;                              
    }
    
    if (strTaskSourceId == null){    
      Scraplr.UI.arrSelectedTask.each(function(obj){ 
        strIdsToRemove = obj.identify();        
        strTaskIdToProcess = Scraplr.Utilities.getTaskIds(strIdsToRemove)[3];
        arrTaskIdsToProcess.push(strTaskIdToProcess);           
      });           
      strIdsToProcess = arrTaskIdsToProcess.join(';');          
      strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strUrlAct+'/'+strIdsToProcess;
    } else if (strTaskSourceId != null){         
      strTaskIdToProcess = Scraplr.Utilities.getTaskIds(strTaskSourceId)[3];
      strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strUrlAct+'/'+strTaskIdToProcess;
    } 
    
    if((strTargetTaskBinId != null)&&(strTaskSourceId != null)){   
      strTaskIdToProcess = Scraplr.Utilities.getTaskIds(strTaskSourceId)[3];
      strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strUrlAct+'/'+strTaskIdToProcess+'?bin='+strTargetTaskBinId;
    }else if((strTargetTaskBinId != null)&&(strTaskSourceId == null)){  
      strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strUrlAct;
    }
    
    Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
      switch(strAct){
        case 'complete':
      
        break;
        case 'remove': 
        Scraplr.UI.arrSelectedTask.each(function(obj){
          obj.hide();          
        });
        break;
        case 'log':
        Scraplr.UI.arrSelectedTask.each(function(obj){
          obj.hide();          
        });
        break;
        case 'publish':
      
        break; 
        case 'move':
        $(strTaskSourceId).hide();
        break;                         
      }
    },function(){      
      switch(strAct){
        case 'complete':
          Scraplr.TaskPaper.clearSelectedTask();
          Scraplr.UI.arrSelectedTask.clear();
        break;
        case 'remove': 
        var strTaskCaptions = Scraplr.Utilities.getSelectedTaskName();   
          console.log('strTaskCaptions after remove:'+strTaskCaptions);
          Scraplr.UI.showDialog ('alert', 'Following task item has been moved to recycler container', strTaskCaptions, function (){}, function (){},true); 
          Scraplr.UI.arrSelectedTask.each(function(obj){
            obj.remove();          
          });  
          Scraplr.TaskPaper.countTaskItem();
          if($$('div.taskItem').length == 0){
            $('taskTagsWrapper').hide();
            $('tagsTokenList').innerHTML = '';
            $('noTask').removeClassName('hidden');
            $('taskPaperWrapper').update('');
            var strTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;  
            switch(strTaskBinId){
              case '1':
                $('noTaskTitle').update('No task todo here yet');
                $('noTaskNote').update('Click "Add Task" button to create one');
              break;
              case '2':
                $('noTaskTitle').update('No task todo here yet');
                $('noTaskNote').update('Click "Add Task" button to create one');
              break; 
              case '3':
                $('noTaskTitle').update('No scheduled task todo here yet');
                $('noTaskNote').update('Click "Add Task" button to create one');
              break; 
              case '5':
                $('noTaskTitle').update('No task todo here yet');
                $('noTaskNote').update('Click "Add Task" button to create one');
              break; 
              case '6':
                $('noTaskTitle').update('No task logged as completed here yet');
                $('noTaskNote').update('');
              break; 
            }
          }
          Scraplr.TaskPaper.clearSelectedTask(); 
          Scraplr.UI.arrSelectedTask.clear();
        break;
        case 'log':
          Scraplr.UI.arrSelectedTask.each(function(obj){
            obj.remove();          
          }); 
          Scraplr.TaskPaper.clearSelectedTask(); 
          Scraplr.TaskPaper.countTaskItem();
          if($$('div.taskItem').length == 0){
            $('taskTagsWrapper').hide();
            $('tagsTokenList').innerHTML = '';
            $('noTask').removeClassName('hidden');
            $('taskPaperWrapper').update('');
          }
          Scraplr.TaskPaper.clearSelectedTask();
          Scraplr.UI.arrSelectedTask.clear();        
        break;
        case 'publish':
          Scraplr.TaskPaper.clearSelectedTask();
          Scraplr.UI.arrSelectedTask.clear();
        break;
        case 'move':
          var strTaskTitle = Scraplr.Utilities.getTaskName(strTaskSourceId);
          var strTaskBinName = '';
          switch(strTargetTaskBinId){
            case '1':
              strTaskBinName = 'Task Container';
            break;
            case '2':
              strTaskBinName = 'Next Container';
            break;
            case '3':
              strTaskBinName = 'Scheduled Container';
            break;
            case '4':
              strTaskBinName = 'Project Container';
            break;
            case '5':
              strTaskBinName = 'Later Container';
            break; 
            case '6':
              strTaskBinName = 'Log Container';
            break;
            case '7':
              strTaskBinName = 'Recycler Container';
            break;                                                           
          }
          Scraplr.UI.showDialog('alert', 'Task "'+strTaskTitle+'" has been moved to '+strTaskBinName, '',function (){}, function (){},true);                
          Scraplr.TaskPaper.clearSelectedTask();
          Scraplr.UI.arrSelectedTask.clear();
        break; 
        case 'empty':
          $$('div.taskItem').invoke('remove');
          $('taskTagsWrapper').hide();
          $('tagsTokenList').innerHTML = '';
          $('noTask').removeClassName('hidden');
          $('taskPaperWrapper').update(''); 
          $('noTaskTitle').update('No task to recycle here yet');
          $('noTaskNote').update('');
        break;                                 
      }                  
    });    
  },
  submitTaskOrder: function (strTaskOrder){
    $('task_order').value = strTaskOrder;
    var strFormTaskOrder = 'formTaskOrder';
    var strTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;       
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/order_task/'+strTaskBinId;                    
    Scraplr.Utilities.caramelizeScrap(strUrl, true, false, strFormTaskOrder, function (){},function(){});    
  },
  countTaskItem: function (){
    var intTasks = 0;
    strCurrentTaskTabId = Scraplr.TaskBins.strActiveTaskBinId;
    if(strCurrentTaskTabId!='4'){
      var intExistingTaskItem = $('taskPaperWrapper').childElements().length;
      if(intExistingTaskItem>0){
        $$('div.taskItem').each(function(objTaskItem){
          intTasks++;                 
        });
      }      
    }else if(strCurrentTaskTabId=='4'){
      $$('div.taskPaperWrapper').each(function(obj){
        intTasks++;           
      });      
    }                       
    switch(strCurrentTaskTabId){
      case '1':
        $('tasksBinNumBadge').update(intTasks);
      break;
      case '2':
        $('nextBinNumBadge').update(intTasks);                              
      break;
      case '3':
        $('scheduledBinNumBadge').update(intTasks);                            
      break;
      case '4':
        $('projectBinNumBadge').update(intTasks);                            
      break;
      case '5':
        $('laterBinNumBadge').update(intTasks);                            
      break;                        
    }    
  },
  checkDue : function (strTargetIds){
    var strSourceDate = $('taskDue'+strTargetIds).value; 
    
    var arrDatetime = strSourceDate.split(' ');
    var arrDate= arrDatetime[0].split('-');
    var arrTime= arrDatetime[1].split(':');
    
    var intDay = parseInt(arrDate[2],10);
    var intMonth = parseInt(arrDate[1],10)-1;
    var intYear = parseInt(arrDate[0],10);      
    
    var intHour = parseInt(arrTime[0],10);
    var intMinute = parseInt(arrTime[1],10);

    var dateDue = new Date(Date.UTC(intYear,intMonth,intDay,intHour,intMinute,0));
    var intDueDateUTC = dateDue.getTime()/1000;                                          

    var dateNow = new Date(Date.UTC(Scraplr.Utilities.dateYear, Scraplr.Utilities.dateMonth-1, Scraplr.Utilities.dateDay, Scraplr.Utilities.timeHours, Scraplr.Utilities.timeMinutes,0)); 
    var intNowDateUTC =  dateNow.getTime()/1000;
    
    if(intNowDateUTC>intDueDateUTC){
      $('taskItemDueRibbon'+strTargetIds).show();
    }
  },
  editDue: function (strTargetIds){
    var strIds = strTargetIds;
    var strTaskId = Scraplr.Utilities.getTaskIds(strIds)[3];
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/edit_due/'+strTaskId;    
    var strFormId = 'formTaskItemDue'+strTargetIds;
    Scraplr.Utilities.caramelizeScrap(strUrl, false, false, strFormId, function (){
    },function(){
      $('taskDue'+strTargetIds).value = $('dueDate'+strTargetIds).value;
      //var strTaskTitle = $('taskItemTitle'+strIds).innerHTML;                 
      //Scraplr.UI.showDialog ('alert', 'new due for task "'+strTaskTitle+'" has been saved','', function (){}, function (){},false);
      Scraplr.TaskPaper.checkDue(strTargetIds);
    });    
  },
  editTag: function (){
    
  },
  setReminder: function (strReminderValue, objSender, strSourceDateTime){ 
    if(strReminderValue != 'at due'){

      var arrReminderData = strReminderValue.split(' ');

      var intReminderValue = Math.abs(parseInt(arrReminderData[0],10));
      var strReminderTime = arrReminderData[1];
      var strReminderReference  = arrReminderData[2]; 
      var dateReminderValue = '', strISODate = '', strHumanizedDate = '';
      //Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes;

      var arrDatetime = strSourceDateTime.split(' '); 
      
      var arrDate= arrDatetime[0].split('-');
      var arrTime= arrDatetime[1].split(':');

      var intDay = parseInt(arrDate[2],10);
      var intMonth = parseInt(arrDate[1],10)-1;
      var intYear = parseInt(arrDate[0],10);      

      var intHour = parseInt(arrTime[0],10);
      var intMinute = parseInt(arrTime[1],10);

      var dateConfig = {minute:intMinute, hour:intHour, day:intDay, month:intMonth, year:intYear};
      console.log(dateConfig);
      var dateConfigDate = Date.today().set(dateConfig);
      //-> bug fix, day is not set to specific day
      var intConfigDay = parseInt(dateConfigDate.toString("dd"),10);
      var intDayValue =  intDay - intConfigDay;
      dateReminderValue = dateConfigDate.addDays(intDayValue);
      
      
      if((/before/i).test(strReminderReference)){ 
        intReminderValue = parseInt(-intReminderValue,10);
      }
  
      if((/^min(ute)?s?/i).test(strReminderTime)){
        dateConfigDate = dateReminderValue; 
        dateReminderValue = dateConfigDate.addMinutes(intReminderValue);
        strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt"); 
        strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm");
        strISODate = dateReminderValue.toISOString().gsub('"','');     
        strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
        //$('humanize').update(strHumanizedDate); 
        if (!strShortDate.startsWith('0NaN')){
          objSender.update(strShortDate);
        }
      }
      if((/^h(our)?s?/i).test(strReminderTime)){
        dateConfigDate = dateReminderValue;
        dateReminderValue = dateConfigDate.addHours(intReminderValue); 
        strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt");
        strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm"); 
        strISODate = dateReminderValue.toISOString().gsub('"','');     
        strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
        //$('humanize').update(strHumanizedDate);
        if (!strShortDate.startsWith('0NaN')){
          objSender.update(strShortDate);
        }      
      }
      if((/^d(ay)?s?/i).test(strReminderTime)){ 
        dateConfigDate = dateReminderValue;
        dateReminderValue = dateConfigDate.addDays(intReminderValue);    
        strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt");
        strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm"); 
        strISODate = dateReminderValue.toISOString().gsub('"','');     
        strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
        //$('humanize').update(strHumanizedDate);
        if (!strShortDate.startsWith('0NaN')){
          objSender.update(strShortDate);
        }      
      }
      if((/^w(eek)?s?/i).test(strReminderTime)){
        dateConfigDate = dateReminderValue;
        dateReminderValue = dateConfigDate.addWeeks(intReminderValue);
        strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt");
        strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm"); 
        strISODate = dateReminderValue.toISOString().gsub('"','');     
        strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
        //$('humanize').update(strHumanizedDate);
        if (!strShortDate.startsWith('0NaN')){
          objSender.update(strShortDate);
        }      
      }
      if((/^mo(nth)?s?/i).test(strReminderTime)){
        dateConfigDate = dateReminderValue;
        dateReminderValue = dateConfigDate.addMonths(intReminderValue);
        strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt");
        strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm"); 
        strISODate = dateReminderValue.toISOString().gsub('"','');     
        strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
        //$('humanize').update(strHumanizedDate);
        if (!strShortDate.startsWith('0NaN')){
          objSender.update(strShortDate);
        }      
      }
      if((/^y(ear)?s?/i).test(strReminderTime)){
        dateConfigDate = dateReminderValue;
        dateReminderValue = dateConfigDate.addYears(intReminderValue);
        strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt");
        strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm"); 
        strISODate = dateReminderValue.toISOString().gsub('"','');     
        strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
        //$('humanize').update(strHumanizedDate);
        if (!strShortDate.startsWith('0NaN')){
          objSender.update(strShortDate);
        }      
      }    
      
    }else if(strReminderValue == 'at due'){
      dateConfigDate = dateReminderValue;
      dateReminderValue = dateConfigDate.addSeconds(1);
      strDateString = dateReminderValue.toString("dddd, MMMM dd, yyyy hh:mm:ss tt");
      strShortDate = dateReminderValue.toString("yyyy-MM-dd HH:mm"); 
      strISODate = dateReminderValue.toISOString().gsub('"','');     
      strHumanizedDate = Scraplr.Utilities.humanizeDate(strISODate);
      //$('humanize').update(strHumanizedDate);
      if (!strShortDate.startsWith('0NaN')){
        objSender.update(strShortDate);
      }    
    }   
  },
  updateReminderLabel: function (){
    
  },
  addTaskTag: function (strObjId, strTagText){     
    var strUserId = Scraplr.Utilities.getUserId();
    var strTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;
    if(!Scraplr.UI.boolNewEntryDialogIsVisible){        
      if((strObjId!=null)&&(strTagText!=null)){
        var strTaskId = Scraplr.Utilities.getTaskIds(strObjId)[3];
        var url = '/'+Scraplr.Utilities.getUserName()+'/request/add_task_tag/'+strTaskId+'?tag='+strTagText;  
        Scraplr.Utilities.caramelizeScrap(url, true, false, null, function (){
        },function(){
          if(Scraplr.Hud.boolTagHudIsVisible){
            Scraplr.UI.setTagHudContent(); 
          }  
          Scraplr.TaskPaper.loadTaskTags(strUserId, strTaskBinId); 
        });      
      }    
    }    
  },
  removeTaskTag: function (obj){  
    var strUserId = Scraplr.Utilities.getUserId();
    var strTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;  
    if(Scraplr.UI.boolNewEntryDialogIsVisible){
      obj.up('li.new-entry-box').remove();
    }else{
      var strTagText = obj.up('li.pui-autocomplete-box').readAttribute('pui-autocomplete:value');
      var strParentId = obj.up('div.taskItemTagBar').identify();  
      var strTaskId = Scraplr.Utilities.getTaskIds(strParentId)[3];
      var url = '/'+Scraplr.Utilities.getUserName()+'/request/remove_task_tag/'+strTaskId+'?tag='+strTagText;  
      Scraplr.Utilities.caramelizeScrap(url, true, false, null, function (){
        obj.up('li.pui-autocomplete-box').hide();
      },function(){ 
        obj.up('li.pui-autocomplete-box').remove();  
        Scraplr.TaskPaper.loadTaskTags(strUserId, strTaskBinId);  
        //console.log('tag for'+strObjId+' removed',strTagText);
      });      
    }
  },
  shareTask: function (objListItem){

    var objCheckBoxMean = objListItem.down('span.shareEnabled');
    
    var strParentId = objListItem.up('div.shareSelectBox').identify();
    var strTaskId = Scraplr.Utilities.getTaskIds(strParentId)[3];    
    
    var strTargetIds = strParentId.gsub('shareSelectorBox','');
    var objMeanSpan = objListItem.down('span.shareItemMeanIco',0);
    var strShareMean = '', strSharePlace ='';
    var strTaskTitle = Scraplr.Utilities.getTaskName('taskItem'+strTargetIds);

    var strMessage = "";
            
    if(objMeanSpan.hasClassName('shareItemScraplr')){
      strShareMean = 'your Scraplr public page';
      strSharePlace = 'scraplr';
    }else if(objMeanSpan.hasClassName('shareItemTwitter')){
        strShareMean = 'your tweets list on Twitter';
        strSharePlace = 'twitter';
    }else if(objMeanSpan.hasClassName('shareItemFacebook')){
        strShareMean = 'your Facebook profile wall';
        strSharePlace = 'facebook';
    }
       
    if(objCheckBoxMean.hasClassName('hidden')){ 
       objCheckBoxMean.removeClassName('hidden');
       //console.log('/'+Scraplr.Utilities.getUserName()+'/request/add_share/'+strTaskId+'/'+strSharePlace);
       strMessage = "share task \""+strTaskTitle+"\" to "+strSharePlace+"?";
       Scraplr.UI.showDialog ('confirm', strMessage, '',function (){
          objCheckBoxMean.addClassName('hidden');
        },function (){
          Scraplr.TaskPaper.shareTaskAct(strTaskId, strSharePlace, 'add');
        }, false);        
    }else if(!objCheckBoxMean.hasClassName('hidden')){
      objCheckBoxMean.addClassName('hidden');
      //console.log('/'+Scraplr.Utilities.getUserName()+'/request/remove_share/'+strTaskId+'/'+strSharePlace);                              
      strMessage = "Stop fetching comment for task \""+strTaskTitle+"\" from "+strShareMean+"?";
      strSubMessage = "Comments posted and related to this task will not be removed.<br/>Please note that this action is not undoable.";
      Scraplr.UI.showDialog ('confirm', strMessage, strSubMessage, function (){
         objCheckBoxMean.removeClassName('hidden');
       },function (){
         Scraplr.TaskPaper.shareTaskAct(strTaskId, strSharePlace, 'remove');
       }, false);     
    }            
  },
  shareTaskAct: function (strTaskId, strSharePlace, strAct){
    var strActControl = '';
    if (strAct == 'add'){
      strActControl = 'add_share';
    }else if (strAct == 'remove'){
      strActControl = 'remove_share';
    }
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strActControl+'/'+strTaskId+'?share='+strSharePlace;
    Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){},function(){});    
  },
  setTaskReminder: function (objListItem){
    var objCheckBoxMean = objListItem.down('span.meanEnabled');

    var strParentId = objListItem.up('div.reminderSelectBox').identify();
    var strTaskId = Scraplr.Utilities.getTaskIds(strParentId)[3];    

    var strTargetIds = strParentId.gsub('reminderSelectorBox','');
    var objMeanSpan = objListItem.down('span.reminderMeanIco',0);
    var strReminderMean = '', strReminderPlace ='';
    var strTaskTitle = Scraplr.Utilities.getTaskName('taskItem'+strTargetIds);

    var strMessage = "";

    if(objMeanSpan.hasClassName('meanByEmail')){
      strReminderMean = 'sending you email';
      strReminderPlace = 'email';
    }else if(objMeanSpan.hasClassName('meanByTweet')){
        strReminderMean = 'sending you tweet';
        strReminderPlace = 'twitter';
    }else if(objMeanSpan.hasClassName('meanByIm')){
        strReminderMean = 'sending you instant message';
        strReminderPlace = 'im';
    }else if(objMeanSpan.hasClassName('meanBySms')){
        strReminderMean = 'sending you text message';
        strReminderPlace = 'sms';
    }
    var strRemindAtValue = $('reminderSelector'+strTargetIds).innerHTML;
    if(objCheckBoxMean.hasClassName('hidden')){ 
       objCheckBoxMean.removeClassName('hidden');
       //console.log('/'+Scraplr.Utilities.getUserName()+'/request/add_share/'+strTaskId+'/'+strReminderPlace);
       strMessage = "add reminder for \""+strTaskTitle+"\" by "+strReminderPlace+"?";
       strSubMessage = "scraplr will remind you by "+strReminderMean;
       Scraplr.UI.showDialog ('confirm', strMessage, strSubMessage,function (){
          objCheckBoxMean.addClassName('hidden');
        },function (){
          Scraplr.TaskPaper.setReminderAct(strTaskId, strReminderPlace, 'add', strRemindAtValue);
        }, false);        
    }else if(!objCheckBoxMean.hasClassName('hidden')){
      objCheckBoxMean.addClassName('hidden');
      //console.log('/'+Scraplr.Utilities.getUserName()+'/request/remove_share/'+strTaskId+'/'+strReminderPlace);                              
      strMessage = "remove "+strReminderPlace+" reminder for \""+strTaskTitle+"\"?";
      strSubMessage = "scraplr won't "+strReminderMean+" anymore.";
      Scraplr.UI.showDialog ('confirm', strMessage, strSubMessage, function (){
         objCheckBoxMean.removeClassName('hidden');
       },function (){
         Scraplr.TaskPaper.setReminderAct(strTaskId, strReminderPlace, 'remove', strRemindAtValue);
       }, false);     
    }
  },
  setReminderAct: function (strTaskId, strReminderPlace, strAct, strRemindAtValue){
    var strActControl = '';
    if (strAct == 'add'){
      strActControl = 'add_reminder';
      var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strActControl+'/'+strTaskId+'?reminder='+strReminderPlace+'&remind_at='+strRemindAtValue;
    }else if (strAct == 'remove'){
      strActControl = 'remove_reminder';
      var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strActControl+'/'+strTaskId+'?reminder='+strReminderPlace;
    }  else if (strAct == 'edit'){
        strActControl = 'edit_reminder';
        var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/'+strActControl+'/'+strTaskId+'?reminder='+strReminderPlace+'&remind_at='+strRemindAtValue;
      }
    
    Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){},function(){});  
  }
};     

Scraplr.TaskMate = {
  arrMateIdData:[],
  countTaskMate: function (strIds){
    var objMateList =  $('taskMateList_'+strIds);
    var intMateNumber = objCommentList.childElements().length;
    var strLabelCaption = '';
    if(intCommentNumber==0){
      strLabelCaption = 'No Task Mate'; 
    }else if(intCommentNumber==1){
      strLabelCaption = '1 Task Mate';
    }else if(intCommentNumber>1){
      strLabelCaption = intCommentNumber+' Task Mates';
    }
    $('taskMateCount_'+strIds).update(strLabelCaption) ; 
  },  
  addTaskMate: function (objTaskItem){    
    console.log(objTaskItem);
    var strParentIdData = objTaskItem.identify().gsub('taskItem_','');
    var newTaskMate = Scraplr.Utilities.objCaramelizedHtml; 
    var arrThisTaskMateList = $('taskMateList_'+strParentIdData).childElements();
    if(arrThisTaskMateList.length > 1){
      var strLastTaskMateId = arrThisTaskMateList.last().identify();
      $(strLastTaskMateId).insert({
         after: newTaskMate
      });
     // Scraplr.TaskComment.scrollToLatestComment($('taskComment_'+strIds),$(strLastTaskMateId));
    }else{
      $('taskMateList_'+strParentIdData).insert(newTaskMate);
      //Scraplr.TaskComment.humanizeTaskCommentDate(arrThisCommentList);
    }
    Scraplr.TaskMate.countTaskMate(strParentIdData);    
  },
  removeTaskMate: function (objSender){
    var strParentIdData = objSender.up('li.taskMateRow').identify().gsub('taskMateRow_','');
    Scraplr.TaskComment.getCommentIdData(strParentIdData);
    var strUserId = Scraplr.TaskMate.arrMateIdData[0];
    var strTaskBinId = Scraplr.TaskMate.arrMateIdData[1];
    var strTaskId = Scraplr.TaskMate.arrMateIdData[2];
    var strMateId = Scraplr.TaskMate.arrMateIdData[3];   
    //var strUrl = 'taskCommentAct.php?strRandom='+Scraplr.Utilities.randomize()+'&strCommentAct=remComment&strUserId='+strUserId+'&strTaskBinId='+strTaskBinId+'&strTaskId='+strTaskId+'&strCommentId='+strCommentId;
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/remove_task_teammate/'+strMateId;
    Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
      //Element.hide(objSender);
      //Element.show('activityIndicator');
    },function(){                  
      var strParentId = objSender.up('li.taskMateRow').identify();
      $(strParentId).remove(); 
      var strIds = strUserId+'_'+strTaskBinId+'_'+strTaskId; 
      Scraplr.TaskMate.countTaskMate(strIds);
    });    
  }  
};

Scraplr.TaskComment = {
  arrCommentIdData:[],
  countTaskComments: function (strParentIdData){  
    var arrThisCommentList = $('taskCommentList_'+strParentIdData).childElements();
    var intTaskComments = arrThisCommentList.length; 
    var strTaskCountText = '';    
    if (intTaskComments==0){
      strTaskCountText = 'No Task comment';
    }else if(intTaskComments==1){
      strTaskCountText = intTaskComments+' Task comment';
    }else if (intTaskComments>1){
      strTaskCountText = intTaskComments+' Task comments';
    }
    $('taskCommentCount_'+strParentIdData).update(strTaskCountText);
  },
  getCommentIdData: function (strCommentRowData){
    Scraplr.TaskComment.arrCommentIdData.clear();    
    Scraplr.TaskComment.arrCommentIdData = strCommentRowData.split("_");    
  }, 
  removeComment: function (objSender){ 
    var strParentIdData = objSender.up('li.taskCommentRow').identify().gsub('taskCommentRow_','');
    Scraplr.TaskComment.getCommentIdData(strParentIdData);
    var strUserId = Scraplr.TaskComment.arrCommentIdData[0];
    var strTaskBinId = Scraplr.TaskComment.arrCommentIdData[1];
    var strTaskId = Scraplr.TaskComment.arrCommentIdData[2];
    var strCommentId = Scraplr.TaskComment.arrCommentIdData[3];   
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/remove_comment/'+strCommentId;
    Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
    },function(){                  
      var strParentId = objSender.up('li.taskCommentRow').identify();
      $(strParentId).fade(); 
      var strIds = strUserId+'_'+strTaskBinId+'_'+strTaskId; 
      Scraplr.TaskComment.countTaskComments(strIds);
    });
  },
  giveCommentPick: function (objSender){
    var strParentIdData = objSender.up('li.taskCommentRow').identify().gsub('taskCommentRow_','');
    Scraplr.TaskComment.getCommentIdData(strParentIdData);
    var strUserId = Scraplr.TaskComment.arrCommentIdData[0];
    var strTaskBinId = Scraplr.TaskComment.arrCommentIdData[1];
    var strTaskId = Scraplr.TaskComment.arrCommentIdData[2];
    var strCommentId = Scraplr.TaskComment.arrCommentIdData[3];    
    Scraplr.UI.showDialog ('confirm', 'Are you sure want to choose the comment as the "owner\'s pick" comment?', '',function (){
    }, function (){       
       var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/pick_comment/'+strCommentId;
       Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
       },function(){          
         objSender.up('div.taskCommentScoreBox').addClassName('taskCommentOwnersPick');
         objSender.up('div.taskCommentScoreBox').innerHTML = '';
         objSender.up('div.taskCommentScoreBox').removeClassName('taskCommentScoreBox');         
       });          
    },false);    
  },
  giveCommentPlus: function (objSender){
    var strParentIdData = objSender.up('li.taskCommentRow').identify().gsub('taskCommentRow_','');
    Scraplr.TaskComment.getCommentIdData(strParentIdData);
    var strUserId = Scraplr.TaskComment.arrCommentIdData[0];
    var strTaskBinId = Scraplr.TaskComment.arrCommentIdData[1];
    var strTaskId = Scraplr.TaskComment.arrCommentIdData[2];
    var strCommentId = Scraplr.TaskComment.arrCommentIdData[3];
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/score_comment/'+strCommentId;
    
    Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
      objSender.previous('img').show();
    },function(){
      objSender.hide(); 
      objSender.previous('img').hide();      
      var strResponse = Scraplr.Utilities.objCaramelizedHtml;
      var strResponseValue = strResponse.split(';');
      var newScoreValue = strResponseValue[0]; 
      $('taskCommentScoreValue_'+strParentIdData).update(newScoreValue);
      strResponseValue.clear();
    });    
  },
  postCommentBack: function (objSender){
    var strParentIdData = objSender.up('div.tasktabPanel').identify().gsub('taskComment_','');
    var strFormId = 'postCommentBack_'+strParentIdData;
    
    if($(strFormId).down('textarea.postCommentBackTextBox').value != ""){
     $(strFormId).down('input.postCommentBackDateBox').value = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes;
     Scraplr.TaskComment.getCommentIdData(strParentIdData);
     var strUserId = Scraplr.TaskComment.arrCommentIdData[0];
     var strTaskBinId = Scraplr.TaskComment.arrCommentIdData[1];
     var strTaskId = Scraplr.TaskComment.arrCommentIdData[2];
     var strCommentId = Scraplr.TaskComment.arrCommentIdData[3];       
     var strIds = strUserId+'_'+strTaskBinId+'_'+strTaskId;
     var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/save_comment/'+strTaskId;
     Scraplr.Utilities.caramelizeScrap(strUrl, false, false, strFormId, function (){
       objSender.next('img.postCommentBackSpinner').removeClassName('hidden');
     },function(){ 
       $(strFormId).down('textarea.postCommentBackTextBox').value="";                
       objSender.next('img.postCommentBackSpinner').addClassName('hidden');       
       var newComment = Scraplr.Utilities.objCaramelizedHtml; 
       var arrThisCommentList = $('taskCommentList_'+strParentIdData).childElements();
       if(arrThisCommentList.length > 1){
         var strLastCommentId = arrThisCommentList.last().identify();
         $(strLastCommentId).insert({
            after: newComment
         });
         Scraplr.TaskComment.scrollToLatestComment($('taskComment_'+strIds),$(strLastCommentId));
       }else{
         $('taskCommentList_'+strParentIdData).insert(newComment);
       }        
       Scraplr.TaskComment.countTaskComments(strIds);       
     });     
    }
    else{
      Scraplr.UI.showDialog ('alert', 'Your comment would be more valuable if it has some words.. :)', '',function (){
      }, function (){ 
        $(strFormId).down('textarea.postCommentBackTextBox').focus();
      },false);      
    }
  },
  humanizeTaskCommentDate: function (arrTaskCommentList){ 
    arrTaskCommentList.each(function(obj){
      var strSourceDate = obj.down('span.taskCommentPostDate').innerHTML;
      var strHumanizedDate = Scraplr.Utilities.getHumanizedDate(strSourceDate);
      obj.down('span.taskCommentPostDate').update(strHumanizedDate);           
    });
    
  },
  scrollToLatestComment: function (container, element){     
    Position.prepare();
    container_y = Position.cumulativeOffset($(container))[1];
    element_y = Position.cumulativeOffset($(element))[1];
    new Effect.Scroll(container, {x:0, y:(element_y-container_y),
    afterFinish: function() { 
      var strIds = $(container).identify().gsub('taskComment','');
      $('task_comment_status'+strIds).value='read';  
      var strTaskItemNewCommentIndyId = $(container).identify().gsub('taskComment','taskItemNewCommentIndy');
      $(strTaskItemNewCommentIndyId).update('');
      var strActiveTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;       
      var strTaskId = Scraplr.Utilities.getTaskIds($(container).identify())[3];
      
      var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/set_comment_status/'+strTaskId;
      var strFormId = $(container).identify().gsub('taskComment','formTaskItemCommentStatus');
      Scraplr.Utilities.caramelizeScrap(strUrl, false, false, strFormId, function (){      
      }, function (){
        
      });      
    }  
    });
  }     
};

Scraplr.TaskRouter = {
  routeTask: function (strTargetTaskBinId){
    var strUrl = ''; 
    var arrTaskIdsToProcess =[];     
    var strIdsToProcess ='';
    var strTaskIdToProcess = ''; 
    var strIdsToMove = '';
    var strContainer = '';  
    if (Scraplr.UI.arrSelectedTask.length == 0){
      Scraplr.UI.showDialog ('alert', 'You have to select at least one task item to route', '',function (){}, function (){},true);	
    }else{       
      switch(strTargetTaskBinId){
        case '2':
          strContainer = 'Next task container';
        break;
        case '3':
          strContainer = 'Scheduled task container';
        break;
        case '5':
          strContainer = 'Later task container';        
        break;
        case '7':
          strContainer = 'Recycle task container';
        break;                         
      }          
      var strTaskCaptions = Scraplr.Utilities.getSelectedTaskName();
      Scraplr.UI.showDialog ('confirm', 'Move following task to '+strContainer+' ?', strTaskCaptions,function (){}, function (){
        Scraplr.UI.arrSelectedTask.each(function(obj){ 
          strIdsToMove = obj.identify();        
          strTaskIdToProcess = Scraplr.Utilities.getTaskIds(strIdsToMove)[3];
          arrTaskIdsToProcess.push(strTaskIdToProcess);           
        });           
        strIdsToProcess = arrTaskIdsToProcess.join(';');          
        strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/move_task/'+strIdsToProcess+'?bin='+strTargetTaskBinId;
        Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
         Scraplr.UI.arrSelectedTask.invoke('hide');
        },function (){
         Scraplr.UI.showDialog ('alert', 'Following task has been moved to '+strContainer, strTaskCaptions,function (){}, function (){},true);
         Scraplr.UI.arrSelectedTask.clear(); 
         arrTaskIdsToProcess.clear();      
        });        
      },false);
    }
  }
};

Scraplr.Hud = {
 boolTagHudIsVisible:false,
 boolMateHudIsVisible:false,
 boolRouterHudIsVisible:false, 
 objTagHud: {},
 initTagHud: function (strHudId, strHudTitle, intTop, intLeft, intWidth, intHeight){
   var strBodyId = $(document.body).identify();
   objWinMan = new ScraplrUI.WindowManager({container: strBodyId});
   Scraplr.Hud.objTagHud = new ScraplrUI.Window({
       id:strHudId,
       top: intTop + Scraplr.Utilities.intTopScrollOffsets, 
       left: intLeft, 
       width: intWidth, 
       height: intHeight, 
       resizable: false, 
       theme: "black_hud", 
       hide: function(el) {
         el.fade({ duration: 0.25 });
         Scraplr.Hud.boolTagHudIsVisible=false; 
       }, 
       windowManager: objWinMan 
     });     
   Scraplr.Hud.objTagHud.setHeader(strHudTitle);
   Scraplr.Hud.objTagHud.bringToFront();
   Scraplr.Hud.objTagHud.observe('move:ended', function (){
     var arrTagHudPos = Scraplr.Hud.objTagHud.getPosition();
     var intTagHudLeft = arrTagHudPos.left;  
     var intTagHudTop = arrTagHudPos.top;  
     if(intTagHudTop<145){
       var intYVal = 145 - intTagHudTop; 
       var strTagHudDomId = Scraplr.Hud.objTagHud.id;
       Scraplr.Hud.moveHud(strTagHudDomId, 0, intYVal, function (){
         Scraplr.Hud.objTagHud.setPosition(145, intTagHudLeft);
       });       
     }
   });       
 },
 objMateHud: {},
 initMateHud: function (strHudId, strHudTitle, intTop, intLeft, intWidth, intHeight){
   var strBodyId = $(document.body).identify();
   objWinMan = new ScraplrUI.WindowManager({container: strBodyId});
   Scraplr.Hud.objMateHud = new ScraplrUI.Window({
       id:strHudId,
       top: intTop + Scraplr.Utilities.intTopScrollOffsets, 
       left: intLeft, 
       width: intWidth, 
       height: intHeight, 
       resizable: false, 
       theme: "black_hud", 
       hide: function(el) {
         Scraplr.Hud.boolMateHudIsVisible=false; 
         el.fade({ duration: 0.25 });         
       }, 
       windowManager: objWinMan 
     });     
   Scraplr.Hud.objMateHud.setHeader(strHudTitle);
   Scraplr.Hud.objMateHud.bringToFront();
   Scraplr.Hud.objMateHud.observe('move:ended', function (){
     var arrMateHudPos = Scraplr.Hud.objMateHud.getPosition();
     var intMateHudLeft = arrMateHudPos.left;  
     var intMateHudTop = arrMateHudPos.top;  
     if(intMateHudTop<145){
       var intYVal = 145 - intMateHudTop; 
       var strMateHudDomId = Scraplr.Hud.objMateHud.id;
       Scraplr.Hud.moveHud(strMateHudDomId, 0, intYVal, function (){
         Scraplr.Hud.objMateHud.setPosition(145, intMateHudLeft);
       });       
     }
   }); 
     
 },
 objRouterHud: {},
 initRouterHud: function (strHudId, strHudTitle, intTop, intLeft, intWidth, intHeight){
   var strBodyId = $(document.body).identify();
   objWinMan = new ScraplrUI.WindowManager({container: strBodyId});
   Scraplr.Hud.objRouterHud = new ScraplrUI.Window({
       id:strHudId,
       top: intTop + Scraplr.Utilities.intTopScrollOffsets, 
       left: intLeft, 
       width: intWidth, 
       height: intHeight, 
       resizable: false, 
       theme: "black_hud", 
       hide: function(el) {
         Scraplr.Hud.boolRouterHudIsVisible=false;
         el.fade({ duration: 0.25 });          
       }, 
       windowManager: objWinMan 
     });     
   Scraplr.Hud.objRouterHud.setHeader(strHudTitle);
   Scraplr.Hud.objRouterHud.bringToFront();
   Scraplr.Hud.objRouterHud.observe('move:ended', function (){
     var arrRouterHudPos = Scraplr.Hud.objRouterHud.getPosition();
     var intRouterHudLeft = arrRouterHudPos.left;  
     var intRouterHudTop = arrRouterHudPos.top;  
     if(intRouterHudTop<145){
       var intYVal = 145 - intRouterHudTop; 
       var strRouterHudDomId = Scraplr.Hud.objRouterHud.id;
       Scraplr.Hud.moveHud(strRouterHudDomId, 0, intYVal, function (){
         Scraplr.Hud.objRouterHud.setPosition(145, intRouterHudLeft);
       });       
     }
   });    
 }, 
 objHelpHud: {},
 initHelpHud: function (strHudId, strHudTitle, intTop, intLeft, intWidth, intHeight){
   var strBodyId = $(document.body).identify();
   objWinMan = new ScraplrUI.WindowManager({container: strBodyId});
   Scraplr.Hud.objHelpHud = new ScraplrUI.Window({
       id:strHudId,
       top: intTop + Scraplr.Utilities.intTopScrollOffsets, 
       left: intLeft, 
       width: intWidth, 
       height: intHeight, 
       resizable: false, 
       theme: "black_hud", 
       hide: function(el) {
         el.fade({ duration: 0.25 }); 
       }, 
       windowManager: objWinMan 
     });     
   Scraplr.Hud.objHelpHud.setHeader(strHudTitle);
   Scraplr.Hud.objHelpHud.bringToFront();
   Scraplr.Hud.objHelpHud.observe('move:ended', function (){
     var arrHelpHudPos = Scraplr.Hud.objHelpHud.getPosition();
     var intHelpHudLeft = arrHelpHudPos.left;  
     var intHelpHudTop = arrHelpHudPos.top;  
     if(intHelpHudTop<145){
       var intYVal = 145 - intHelpHudTop; 
       var strHelpHudDomId = Scraplr.Hud.objHelpHud.id;
       Scraplr.Hud.moveHud(strHelpHudDomId, 0, intYVal, function (){
         Scraplr.Hud.objHelpHud.setPosition(145, intHelpHudLeft);
       });       
     }
   });       
 },  
 handleHudScrollReposition: function (){
   Event.observe(window,'scroll', function(event){                  
     if(Scraplr.UADetector.Browser === 'Safari'){
       Scraplr.Utilities.intTopScrollOffsets =  document.viewport.getScrollOffsets().top;
       Scraplr.Hud.objTagHud.options.top = 145 + Scraplr.Utilities.intTopScrollOffsets;
       try{ 
         Element.absolutize($('tagHud'));
         $('tagHud').setStyle({ top: 145 + Scraplr.Utilities.intTopScrollOffsets + 'px' });
       }catch(ex){}
     } else if (!Scraplr.UADetector.Browser === 'Safari'){
     }                    
   });   
 }, 
 moveHud: function (objHudDomId, intX, intY, callback){
   new Effect.Move($(objHudDomId).identify(), { x: intX, y: intY, duration: 0.25, fps: 100, transition: Effect.Transitions.easeInOutSine, 
     afterFinish: function (){
      callback();
     }
   });   
 },
 addTag: function (){
   var strTagText = $('tag_name').value;   
   if((strTagText!='Tag Name')&&(strTagText!='')){
     var url = '/'+Scraplr.Utilities.getUserName()+'/request/create_tag/?tag[name]='+strTagText;  
     Scraplr.Utilities.caramelizeScrap(url, false, false, null, function (){ 
       $('addTagSpinner').show();
     },function(){
       $('addTagSpinner').hide();         
       var newTag = Scraplr.Utilities.objCaramelizedHtml; 
       var arrThisTagList = $('tagList').childElements(); 
       if(arrThisTagList.length > 1){
         var strLastTagId = arrThisTagList.last().identify();
         $(strLastTagId).insert({
            after: newTag
         }); 
       }else{
         $('tagList').insert(newTag); 
       }
       $('tag_name').value = 'Tag Name';
       Scraplr.Hud.initTagHudListItem();  
     });     
   }
 },
 removeTag: function (objTagListItemRemoveButton){
   var strTagId = objTagListItemRemoveButton.up('li.tagListItem').identify();
   var url = '/'+Scraplr.Utilities.getUserName()+'/request/remove_tag/'+strTagId.gsub('taskTag_','');  
   Scraplr.Utilities.caramelizeScrap(url, true, false, null, function (){
     objTagListItemRemoveButton.up(0).hide();
   },function(){
     $('tag_name').value = 'Tag Name'; 
     objTagListItemRemoveButton.up(0).remove();
     $$('li.tagListItem').each(function(obj){
       obj.removeClassName('alternateTagRow');           
     });
     Scraplr.Hud.initTagHudListItem();
   });   
 },
 initTagHudListItem: function (){
   var i = 1;
   $$('li.tagListItem').each(function(obj){
     
     if (i%2 == 0){                  
       
       obj.addClassName('alternateTagRow');       
     }      
     new Draggable(obj, { 
       superghosting:true,   
       onStart: function (item){
          
         Scraplr.UI.isDragging = true;
         item.element.addClassName('isDragged');
       },
       onEnd: function (item){         
         //$$('div.taskItem').each(function(obj){ 
           Scraplr.UI.isDragging = false;
           item.element.removeClassName('isDragged');           
         //});
       },
       starteffect: function (){},
       endeffect: function (){}        
     });
     i++;
   });    
 },
 addMate: function (){
   var strMateName = $('teammate_name').value;
   var strMateEmail = $('teammate_email').value;   
   if((strMateName!='Name')&&(strMateName!='')){
     var url = '/'+Scraplr.Utilities.getUserName()+'/request/create_teammate/?teammate[name]='+strMateName+'&teammate[email]='+strMateEmail;  
     Scraplr.Utilities.caramelizeScrap(url, false, false, null, function (){ 
       $('addMateSpinner').show();
     },function(){
       $('addMateSpinner').hide();         
       var newMate = Scraplr.Utilities.objCaramelizedHtml; 
       var arrThisMateList = $('mateList').childElements(); 
       if(arrThisMateList.length > 1){
         var strLastMateId = arrThisMateList.last().identify();
         $(strLastMateId).insert({
            after: newMate
         }); 
       }else{
         $('mateList').insert(newMate); 
       }
       $('teammate_name').value = 'Name';
       $('teammate_email').value = 'Email';
       Scraplr.Hud.initMateHudListItem();
       $('teammate_name').focus();  
     });     
   }
 },
 removeMate: function (objMateListItemRemoveButton){
   var strMateId = objMateListItemRemoveButton.up('li.taskMateListItem').identify();
   var url = '/'+Scraplr.Utilities.getUserName()+'/request/remove_teammate/'+strMateId.gsub('taskMate_','');  
   Scraplr.Utilities.caramelizeScrap(url, true, false, null, function (){ 
     objMateListItemRemoveButton.up(0).hide();
   },function(){ 
     objMateListItemRemoveButton.up(0).remove();
     $$('li.taskMateListItem').each(function(obj){
       obj.removeClassName('alternateTaskMateRow');           
     });
     $('teammate_name').value = 'Name';
     $('teammate_email').value = 'Email';
     Scraplr.Hud.initMateHudListItem(); 
   });   
 }, 
 initMateHudListItem: function (){
   var i = 1;
   $$('li.taskMateListItem').each(function(obj){
     if (i%2 == 0){
       obj.addClassName('alternateTaskMateRow');
     }      
     new Draggable(obj, { 
       superghosting:true,   
       onStart: function (item){
         console.log('startDragging',item.element.identify()); 
         Scraplr.UI.isDragging = true;
         item.element.addClassName('isDragged');
       },
       onEnd: function (item){         
         //$$('div.taskItem').each(function(obj){ 
           Scraplr.UI.isDragging = false;
           item.element.removeClassName('isDragged');           
         //});
       },
       starteffect: function (){},
       endeffect: function (){}        
     });
     i++;
   });    
 }  
};            
     
Scraplr.UI = { 
  strNewEntryTitleBoxInactiveColor : "#CCCCCC",
  strNewEntryTitleBoxActiveColor : "#666666",
  arrSelectedTask:[],
  taskItemToolTip : {},
  strCurrentActiveTaskBin:'1', // 1 -> Task Bin, 2 -> Next ... so forth 
  isDragging:false,
  viewportwidth:0,
  viewportheight:0,
  boolDialogIsVisible : false,
  boolDialogIsSliding : false,
  boolPreferencesIsVisible : false,
  boolNewEntryDialogIsVisible:false,
  boolSlideRightTagIsEnabled :true,
  boolSlideLeftTagIsEnabled: false,
  boolTagBarIsSliding: false,
  arrTaskItemDivs :[],
  arrDialogCallbacks: [],
  initWorkspace: function (strUserId){
    if (typeof window.innerWidth != 'undefined') {
      Scraplr.UI.viewportwidth = window.innerWidth;
      Scraplr.UI.viewportheight = window.innerHeight;
    }
    else if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.clientWidth !== 'undefined' && document.documentElement.clientWidth !== 0) {
      Scraplr.UI.viewportwidth = document.documentElement.clientWidth;
      Scraplr.UI.viewportheight = document.documentElement.clientHeight;
    }
    else {
      Scraplr.UI.viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
      Scraplr.UI.viewportheight = document.getElementsByTagName('body')[0].clientHeight;
    }
    //var strBackImageUrl =  'img/'+Scraplr.Prefs.strBackdropPath;
    //$('scraplr_'+strUserId).setStyle('background-image: url('+strBackImageUrl+') fixed'); 
    
     
    $('header').setStyle('width:'+ Scraplr.UI.viewportwidth + "px;");
    $('tagsBarShade').setStyle('width:'+ Scraplr.UI.viewportwidth + "px;");
    $('activityIndicator').setStyle('left:'+  Math.floor((Scraplr.UI.viewportwidth/2) - (150/2 )) + 'px;');
    $('activityIndicator').setStyle('top:'+  Math.floor((Scraplr.UI.viewportheight/2) - (150/2 )) + 'px;');
        
    $('newEntryDialogOverlay').setStyle('top:'+  $('topBar').offsetHeight + "px;"); 
    $('newEntryDialogOverlay').setStyle('height:'+ parseInt(Scraplr.UI.viewportheight - ($('topBar').offsetHeight),10) + 'px;');
    $('newEntryDialogOverlay').setStyle('width:'+  Scraplr.UI.viewportwidth + 'px;');
    
    $('userDialog').setStyle('left:'+  Math.floor((Scraplr.UI.viewportwidth/2) - (440/2 )-10) + 'px;');
    $('userPreferences').setStyle('left:'+  Math.floor((Scraplr.UI.viewportwidth/2) - (508/2 )-10) + 'px;');
    $('newEntryDialog').setStyle('left:'+  Math.floor((Scraplr.UI.viewportwidth/2) - (668/2 )-10) + 'px;');    
    
    $('appSpinner').setStyle('left:'+  Math.floor((Scraplr.UI.viewportwidth/2) - (110/2 )-10) + 'px;');
    $('appSpinner').setStyle('top:'+  Math.floor((Scraplr.UI.viewportheight/2) - (30/2 )-10) + 'px;');
    
  },
  initAppMainCommandButons: function (){
      
    
    $('cmdAppHelp').observe('click',function(event){
      /*Scraplr.Hud.objHelpHud.show().setAjaxContent('help.html', {
        method: "GET", 
        onCreate: function() {   
          this.setContent('<img id="spinnerAnimated" src="img/spinner.gif" />');   
        },
        onComplete: function (){
 
        }
      });*/
      Scraplr.Utilities.redirect('http://support.scraplr.com');	
    // end observe click
    });
    
    if($('cmdAppAdmin') != null){
      $('cmdAppAdmin').observe('click',function(event){	
         var strUrl = '/'+Scraplr.Utilities.getUserName()+'/admin/';         
         Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
           //Element.show('activityIndicator');
         },function(){
           Scraplr.Utilities.redirect('/'+Scraplr.Utilities.getUserName()+'/admin/');
         });         
         
      // end observe click
      });
    } else if($('cmdAppMember') != null){
      $('cmdAppMember').observe('click',function(event){	
         var strUrl = '/'+Scraplr.Utilities.getUserName()+'/';         
         Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
           //Element.show('activityIndicator');
         },function(){
           Scraplr.Utilities.redirect('/'+Scraplr.Utilities.getUserName()+'/');
         });         
         
      // end observe click
      });
    }
    $('cmdAppPref').observe('click',function(event){
      if(!Scraplr.UI.boolPreferencesIsVisible){
        Scraplr.UI.toggleDialog('userPreferences','show', function (){
          Scraplr.UI.boolPreferencesIsVisible = true;
        },298);
      }
    });
    $('cmdAppLogout').observe('click',function(event){	
      Scraplr.UI.showDialog ('confirm', 'Are you sure want to logout from Scraplr?', '',function (){
      }, function (){
         var strUrl = '/signout'; 
         //Scraplr.Utilities.redirect(strUrl);
                 
         Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
         },function(){
           Scraplr.Utilities.redirect('/');
         });         
         
      },false);
    // end observe click
    });    
  },
  initTaskCommandDroppables: function (){
    // Command Button accept drop
    Droppables.add('cmdTaskComplete', {
      accept: 'taskItem',
      onDrop: function(element,event) {
        //var objTarget = element.identify();
        //element.removeClassName('isDragged');
        
        Scraplr.TaskPaper.toggleChecked(element.down('div.taskItemCheck'),event);
      },
      hoverclass: 'taskCmdBtOnReadyDrop'
    });
    Droppables.add('cmdTaskRemove', {
      accept: 'taskItem',
      onDrop: function(element) { 
        var objTarget = element.identify();
        var strTaskTitle = element.down('div.taskItemTitle').innerHTML;        
        Scraplr.UI.showDialog ('confirm', 'Are you sure want to remove task "'+strTaskTitle+'"?', '',function (){           
           element.show();
        }, function (){           
           element.removeClassName('isDragged');
           element.hide();
           Scraplr.TaskPaper.processTask('remove', objTarget, null);
        },false);                
      },
      hoverclass: 'taskCmdBtOnReadyDrop'
    });  
    Droppables.add('cmdTaskLog', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('log', objTarget, null);
      },
      hoverclass: 'taskCmdBtOnReadyDrop'
    });
    
    Droppables.add('cmdTaskPublish', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('publish', objTarget, null);
      },
      hoverclass: 'taskCmdBtOnReadyDrop'
    });      
    // Task tab accept drop
  },
  initTaskItemDraggable: function (){
    $$('div.taskItem').each(function(obj){
      
      //obj.down()
      var objTaskItem = obj;
      new Draggable(obj, { 
        revert:true,
        handle:'taskItemDragHandle',   
        onStart: function (item){ 
          Scraplr.UI.isDragging = true;
          $$('div.ScraplrUI-widget-dropdown').invoke('remove');
          item.element.addClassName('isDragged');
        },
        onEnd: function (item){
          
          //$$('div.taskItem').each(function(obj){ 
            Scraplr.UI.isDragging = false;
            item.element.removeClassName('isDragged');           
          //});
        },
        starteffect: function (){},
        endeffect: function (){}        
      }); 
      
      Droppables.add(objTaskItem.identify(), {
        accept: 'tagListItem',
        onDrop: function(element) { 
          var strTagTextSource = element.innerHTML.split('<');
          var strTagText = strTagTextSource[0];       

          var strTaskId = Scraplr.Utilities.getTaskIds(objTaskItem.identify())[3];
          var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/add_task_tag/'+strTaskId+'?tag='+strTagText;
          
            if(objTaskItem.hasClassName('folded')){
              Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
                //onCreateXHR
              },function(){
                Scraplr.TaskPaper.toggleFold(objTaskItem);// in life app, detail data should already contained newly added tag
              });            
            }else if(objTaskItem.hasClassName('unfolded')){
              var strTagsContainerId = objTaskItem.identify().gsub('taskItem_','');          
              var intExistingTokens = $('taskItemTags_'+strTagsContainerId).down('ul.pui-autocomplete-holder').childElements().size(); 
              var objExistingTokens = $('taskItemTags_'+strTagsContainerId).down('ul.pui-autocomplete-holder').childElements();

              var strTaskItemTitle = Scraplr.Utilities.getTaskName(objTaskItem.identify());

              if(intExistingTokens>1){ 
                objExistingTokens.each(function(obj){
                  if(obj.hasClassName('pui-autocomplete-box')){
                    var arrTokenContent = obj.down('span').innerHTML.split('<');
                    var strTag = arrTokenContent[0];
                    if(strTagText.toLowerCase() == strTag.toLowerCase()){
                      Scraplr.UI.showDialog ('alert', 'Task "'+strTaskItemTitle+'" already has "'+strTagText+'" tag', '',function (){}, function (){},false);                
                    }else{
                      var objTarget = objTaskItem.down('ul.pui-autocomplete-holder').next(0).identify();                                   
                      Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
                        //onCreateXHR
                      },function(){
                        Scraplr.TaskPaper.createUnexistTagToken(objTarget, strTagText);
                      });                                      
                    } 
                  }                 
                });
                strTagTextSource.clear();
              }else{   
                Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
                  //onCreateXHR
                },function(){ 
                  var objTarget = objTaskItem.down('ul.pui-autocomplete-holder').next(0).identify();
                  Scraplr.TaskPaper.createUnexistTagToken(objTarget, strTagText);
                });                                                 
              }            
            }
          strTagTextSource.clear();          
        },
        hoverclass: 'taskItemOnReadyDropTag'
      });

      Droppables.add(obj.identify(), {
        accept: 'taskMateListItem',
        onDrop: function(element) {
          var strMateText = element.down('span.taskMateNameLabel').innerHTML; 
          var strMateId = element.identify().gsub('clone_task_','');
          var strTaskId = Scraplr.Utilities.getTaskIds(obj.identify())[3];
          var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/add_task_teammate/'+strTaskId+'?teammate[name]='+strMateText;
          if(obj.hasClassName('unfolded')){                                               
            Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
              //onCreateXHR
            },function(){
              Scraplr.TaskMate.addTaskMate(obj);
            });                    
          }else{
              Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
                //onCreateXHR
              },function(){
                Scraplr.TaskPaper.toggleFold(obj);
              });            
          }
        },
        hoverclass: 'taskItemOnReadyDropMate',
        onHover: function (obj){
          console.log(objTaskItem);    
          if(objTaskItem.hasClassName('unfolded')){
            var strParentId = objTaskItem.identify().gsub('taskItem_','');
            var boolTabTaskMateIsActive = $('taskItemTab_'+strParentId).down('li.taskMateValue').hasClassName('selectedTaskTab');
            if(!boolTabTaskMateIsActive){
              $('taskComment_'+strParentId).hide();
              $('taskMate_'+strParentId).show(); 
              $('taskItemTab_'+strParentId).down('li.taskMateValue').addClassName('selectedTaskTab');
              $('taskItemTab_'+strParentId).down('li.taskCommentValue').removeClassName('selectedTaskTab'); 
            }
          }
        }
      });      
      
    });   
  },
  initTaskTabItemDroppables: function (){
    Droppables.add('tasksBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget, '1');
      },
      hoverclass: 'taskTabOnReadyDrop'
    });                 
    
    Droppables.add('nextBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget, '2');        
      },
      hoverclass: 'taskTabOnReadyDrop'
    });
    
    Droppables.add('scheduledBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget, '3');        
      },
      hoverclass: 'taskTabOnReadyDrop'
    }); 
    
    /*Droppables.add('projectBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget, '4');        
      },
      hoverclass: 'taskTabOnReadyDrop'
    });*/
    
    Droppables.add('laterBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget, '5');        
      },
      hoverclass: 'taskTabOnReadyDrop'
    });
    
    Droppables.add('recycleBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget ,'6');        
      },
      hoverclass: 'taskTabAuxOnReadyDrop'
    });  
    
    Droppables.add('completedBin', {
      accept: 'taskItem',
      onDrop: function(element) {
        var objTarget = element.identify();
        element.removeClassName('isDragged');
        Scraplr.TaskPaper.processTask('move', objTarget, '7');        
      },
      hoverclass: 'taskTabAuxOnReadyDrop'
    });
                        
  },
  initSortableTaskItems: function (){
      if(Scraplr.TaskBins.strActiveTaskBinId !== '4'){
        Sortable.create('taskPaperWrapper',{tag:'div', constraint:false, only: ['taskItem'], handle:'taskItemDragHandle',//tree:true, treeTag:'div',
          onUpdate: function(list) {
            var strUserId = Scraplr.Utilities.getUserId();  
            var strTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;
            var strTaskItemId = 'taskItem_'+strUserId+'_'+strTaskBinId+'_';
            var strTaskItemOrder = Sortable.serialize(list).gsub('taskPaperWrapper[]=',strTaskItemId).gsub('&',';');
            Scraplr.TaskPaper.submitTaskOrder(strTaskItemOrder);
          }    
        });           
        
      } else if (Scraplr.TaskBins.strActiveTaskBinId === '4'){ 
        $$('div.projectItemWrapper').each(function(obj){                                                                              
          Sortable.create(obj.identify(),{tag:'div', constraint:'vertical', only: ['taskItem'], handle:'taskItemDragHandle',
            onUpdate: function(list) {
              console.log(Sortable.serialize(list));
            }    
          });
        });        
        Sortable.create('taskPaperWrapper',{tag:'div', constraint:'vertical', only: ['projectItemWrapper'], handle:'projectItemWrapperTitle',//tree:true, treeTag:'div',
          onUpdate: function(list) {
            console.log(Sortable.serialize(list));
          }    
        });
      }
  },
  initTaskPaperFoldHandler: function (){
    $$('div.taskItem').each(function(obj){           
      obj.observe('click',function(event){
        if(obj.hasClassName('folded')){
          Scraplr.TaskPaper.toggleSelected(obj, event);	
        }
      // end observe click
      });
      obj.observe('dblclick',function(event){        	
        Scraplr.TaskPaper.toggleFold(obj);        
        //Scraplr.TaskPaper.toggleEditTaskTitle(obj);
      // end observe dblclick
      });           
    });
  },
  initSelectedTaskIndy: function (){
    $$('div.itemSelectIndy').invoke('hide');
  },
  initTaskPaperTitleEdit: function (){ 
    $$('div.taskTitleLabel').invoke('hide');
    $$('div.taskItem').each(function(objTaskItem){
      var strIds = objTaskItem.identify().gsub('taskItem','');
      var strTaskId = Scraplr.Utilities.getTaskIds(strIds)[3];
      var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/edit_title/'+strTaskId;
      var objTaskItemTitleEditor =  new Ajax.InPlaceEditorWithEmptyText('taskItemTitle'+strIds, strUrl,{highlightColor:'#efefef',highlightEndColor:'#efefef', fieldId:'task_title', paramName: 'task[title]', emptyText:'click to add title for this task',
      callback: function(form, value) { 
        return 'task[title]=' + encodeURIComponent(value);
      },
      onComplete: function (response){
        var strResponse = response.responseText;
        var strResponseValue = strResponse.split(';'); 
        $('taskItemTitle'+strIds).update(strResponseValue[0]);
        $('taskItemTitleLabel'+strIds).update($('taskItemTitle'+strIds).innerHTML);
        if(objTaskItem.hasClassName('folded')){
           $('taskItemTitle'+strIds).hide();
        }
        strResponseValue.clear();
      }
      });
      $('taskItemTitle'+strIds).hide();
      $('taskItemTitleLabel'+strIds).show();      
    });    
  },
  initTaskPaperNoteEdit: function (strTargetIds){
    var strTaskId = Scraplr.Utilities.getTaskIds(strTargetIds)[3];
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/edit_note/'+strTaskId;
    var taskPaperNoteEditor = new Ajax.InPlaceEditorWithEmptyText('taskItemNote'+strTargetIds, strUrl,{highlightColor:'#f8f8f8',highlightEndColor:'#f8f8f8', rows:4, cols:85, fieldId:'task_note', parameName: 'task[note]', emptyText:'click to add note for this task',
    callback: function(form, value) {
      return 'task[note]=' + encodeURIComponent(value); 
    },
    onComplete: function (response){
      var strResponse = response.responseText;
      var strResponseValue = strResponse.split(';'); 
      $('taskItemNote'+strTargetIds).update(strResponseValue[0]); 
      strResponseValue.clear();     
    }
    });     
  },
  initTaskItemTabs: function (strTargetIds){
      new ScraplrTabs('taskItemTab'+strTargetIds, {
         defaultPanel: 'taskComment'+strTargetIds
       });                     
  }, 
  initTaskTabLabelClickHandler: function (){
    $$('span.profileTabLabel').each(function(obj){
      var strObjParentId = obj.up('ul').identify().gsub('taskItemTab_','');
      obj.observe('click',function(event){ 
        $('reminderSelectorBox_'+strObjParentId).hide();
        $('dueDateSelector_'+strObjParentId).hide();
      // end observe click
      });           
    });
  },
  initTaskBinNumBadge: function (){
    var intTaskNumbers = $$('div.taskItem').length;
    if((Scraplr.TaskBins.strActiveTaskBinId!='4')&&(intTaskNumbers == 0)){
      switch(Scraplr.TaskBins.strActiveTaskBinId){
        case '1':
          $('tasksBinNumBadge').addClassName('hidden');
          $('tasksBinNumBadge').update(intTaskNumbers);
        break;
        case '2':
          $('nextBinNumBadge').addClassName('hidden');
          $('nextBinNumBadge').update(intTaskNumbers);
        break;
        case '3':
          $('scheduledBinNumBadge').addClassName('hidden');
          $('scheduledBinNumBadge').update(intTaskNumbers);
        break; 
        case '5':
          $('laterBinNumBadge').addClassName('hidden');
          $('laterBinNumBadge').update(intTaskNumbers);
        break;                                   
      }
    }else if((Scraplr.TaskBins.strActiveTaskBinId!='4')&&(intTaskNumbers > 0)){
      switch(Scraplr.TaskBins.strActiveTaskBinId){
        case '1':
          $('tasksBinNumBadge').removeClassName('hidden');
          $('tasksBinNumBadge').update(intTaskNumbers);
        break;
        case '2':
          $('nextBinNumBadge').removeClassName('hidden');
          $('nextBinNumBadge').update(intTaskNumbers);
        break;
        case '3':
          $('scheduledBinNumBadge').removeClassName('hidden');
          $('scheduledBinNumBadge').update(intTaskNumbers);
        break; 
        case '5':
          $('laterBinNumBadge').removeClassName('hidden');
          $('laterBinNumBadge').update(intTaskNumbers);
        break;                                   
      }
    }
    
    var intProjectNumbers = $('div.projectItemWrapper').length;    
    if((Scraplr.TaskBins.strActiveTaskBinId=='4')&&(intProjectNumbers == 0)){     
      $('projectBinNumBadge').addClassName('hidden');
      $('projectBinNumBadge').update(intTaskNumbers); 
    }else if((Scraplr.TaskBins.strActiveTaskBinId=='4')&&(intProjectNumbers > 0)){     
      $('projectBinNumBadge').removeClassName('hidden');
      $('projectBinNumBadge').update(intTaskNumbers); 
    }    
  },
  initNewEntryDialogHandler: function (){
    $('newEntryTitleBox').observe('keyup',function(event){
      	
      if($('newEntryTitleBox').value !== "Type your new task name here"){
        $('newEntryTitleBox').style.color = Scraplr.UI.strNewEntryTitleBoxActiveColor ;                          
      }       
      if($('newEntryTitleBox').value === "Type your new task name here"){
        $('newEntryTitleBox').value = ""; 
      }
      // FF and Safari, focused text box placed cursor at the end of the words while IE at the beginning. So, an 'OR' should work
      if(($('newEntryTitleBox').value.startsWith('Type your new task name here'))||($('newEntryTitleBox').value.endsWith('Type your new task name here'))){
        $('newEntryTitleBox').value = $('newEntryTitleBox').value.gsub('Type your new task name here',''); 
      }      
    });
    
    Scraplr.UI.initTextValueSwitcher($('newItemNote'), 'Task note', function (){}, true);
           
    $('newEntryTitleBox').observe('blur',function(event){	
      if($('newEntryTitleBox').value === ""){     
        $('newEntryTitleBox').style.color = Scraplr.UI.strNewEntryTitleBoxInactiveColor ; 
        $('newEntryTitleBox').value = "Type your new task name here" ;
        $('newEntryTitleBox').focus();
      }
    // end observe blur
    });     
    $('newEntryTitleBox').observe('click',function(event){	
      if($('newEntryTitleBox').value === "Type your new task name here"){     
        $('newEntryTitleBox').style.color = Scraplr.UI.strNewEntryTitleBoxActiveColor ;                  
        $('newEntryTitleBox').value = "";
      }
    // end observe focus
    });    
 
        
    // setup reminder popup box trigger 
    Scraplr.UI.initReminderMeanCheckList('New');
    $('reminderSelectorBoxNew').hide();
    $('newReminderTrigger').observe('click',function(event){
	    $('newDueDateSelector').hide();
	    $('newTaskShareSelector').hide(); 
	    $('newRecurringStartDateSelector').hide();     
      $('reminderSelectorBoxNew').toggle(); 
      try{
        $('newReminderValue').focus();
      } catch(ex){
        log: Prototype.emptyFunction;
      }
    // end observe click
    });    
            
    // setup datetime picker
    $('newDueDate').value = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay; 
    $('newDueTime').value = Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes;
    $('newDuePicker').innerHTML = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes; 
    $('taskDueAt').value = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes; 
   
    Scraplr.TaskPaper.setReminder('2 Hours before', $('newReminderDateTime'), $('taskDueAt').value);
   
    $('newDuePicker').observe('click',function(event){ 
      // close any open reminder select box
      $('reminderSelectorBoxNew').hide(); 
      $('newTaskShareSelector').hide(); 
      $('newRecurringStartDateSelector').hide();
      $('newDueDateSelector').toggle();
      	
    // end observe click
    });    
    $('newDueDateSelector').hide();
    dueCal = new ScraplrUI.Calendar($('newDueDateSelector').identify(),{format: Scraplr.Utilities.strDateFormat});    
    
    dueCal.observe('click',function(e) {   
      var strDueTime = $('newDueTime').value;        
      if((strDueTime != '') && (/^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$/).test(strDueTime)){
        $('newDuePicker').innerHTML = e.memo.formattedDate +' '+strDueTime;
        $('newDueDate').value = e.memo.formattedDate; 
        $('taskDueAt').value = e.memo.formattedDate +' '+strDueTime; 
        Scraplr.TaskPaper.setReminder('2 Hours before', $('newReminderDateTime'), $('taskDueAt').value);          
      }else{
        $('newDueTime').value ="";
        $('newDueTime').focus();
        /*Scraplr.UI.showDialog ('alert', 'Time format is invalid', 'Please use one of the following format:<br/> hh:mm or hh:mm am/pm',function (){}, function (){
          $('newDueTime').value ="";
          $('newDueTime').focus();
        },false);*/
      }        
    });
    
    dueCal.observe('dblclick',function(event){
      event.stop();
    }); 
    
    $('newDueTime').observe('keyup',function(event){
      var strDueTime = $('newDueTime').value;
      if((strDueTime != '') && (/^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$/).test(strDueTime)){	
        $('newDuePicker').innerHTML = $('newDueDate').value +' '+$('newDueTime').value;
        $('taskDueAt').value = $('newDueDate').value + ' '+$('newDueTime').value; 
        Scraplr.TaskPaper.setReminder('2 Hours before', $('newReminderDateTime'), $('taskDueAt').value);
      }
    });
    
    new HotKey('enter',function(e){
      var strDueTime = $('newDueTime').value;
      if((strDueTime != '') && (/^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$/).test(strDueTime)){
        $('newDuePicker').innerHTML = $('newDueDate').value + ' '+$('newDueTime').value;
        $('taskDueAt').value = $('newDueDate').value + ' '+$('newDueTime').value;          
      }
  	},{element:$('newDueTime').identify()});

    // setup recurring start datetime picker
    $('newRecurringTimeValue').value = Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes;
    $('newRecurringStartPicker').innerHTML = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay;
    $('newRecurringStartPicker').observe('click',function(event){ 
      // close any open reminder select box
      $('reminderSelectorBoxNew').hide(); 
      $('newTaskShareSelector').hide(); 
       $('newDueDateSelector').hide();
      $('newRecurringStartDateSelector').toggle();	
    // end observe click
    });    
    $('newRecurringStartDateSelector').hide();
    recurrStartCal = new ScraplrUI.Calendar($('newRecurringStartDateSelector').identify(),{format: Scraplr.Utilities.strDateFormat});
    recurrStartCal.observe('click',function(e) {
      $('newRecurringStartPicker').innerHTML = e.memo.formattedDate;
      $('newRecurringStartDateSelector').toggle();
    });
    
    Scraplr.UI.initShareMeanCheckList();
    
    //init reminder picker
    
    $('newReminderValue').observe('keyup',function(event){	
      var strReminderValue = $('newReminderValue').value;
      Scraplr.TaskPaper.setReminder(strReminderValue, $('newReminderDateTime'), $('taskDueAt').value); 
    });
    
    
    
    //setup share selector
    $('newTaskShareSelector').hide();
    $('newTaskShare').observe('click',function(event){ 
      $('newDueDateSelector').hide();     
      $('reminderSelectorBoxNew').hide();
      $('newRecurringStartDateSelector').hide(); 
      $('newTaskShareSelector').toggle();
    // end observe click
    });    
    
    Scraplr.UI.initTagsEntryBox('New');
    
    $('newEntryDialogMoreTogglerWrapper').observe('click',function(event){
      var isInLessState = $('newEntryDialog').hasClassName('newEntryDialogLess');
      var isInMoreState = $('newEntryDialog').hasClassName('newEntryDialogMore');
      if(isInLessState){
        $('newEntryDialog').removeClassName('newEntryDialogLess');
        $('newEntryDialog').addClassName('newEntryDialogMore');
        $('newEntryDialogMoreTogglerDisc').removeClassName('newEntryLessDetail');
        $('newEntryDialogMoreTogglerDisc').addClassName('newEntryMoreDetail');
        $('newEntryDialogMoreWrapper').removeClassName('hidden');
        $('newEntryDialogMoreTogglerLabel').update('Less detail for this entry');
      }else if(isInMoreState){
        $('newEntryDialog').addClassName('newEntryDialogLess');
        $('newEntryDialog').removeClassName('newEntryDialogMore');
        $('newEntryDialogMoreTogglerDisc').addClassName('newEntryLessDetail');
        $('newEntryDialogMoreTogglerDisc').removeClassName('newEntryMoreDetail');
        $('newEntryDialogMoreWrapper').addClassName('hidden');
        $('newEntryDialogMoreTogglerLabel').update('More detail for this entry');
      }	
    // end observe click
    });
    
    new HotKey('enter',function(e){ 
      if(($('newEntryTitleBox').value !== "Type your new task name here")&&($('newEntryTitleBox').value !== "")){
        Scraplr.UI.postNewEntry();
      }
  	},{element:$('newEntryTitleBox').identify()});      

    $('newEntryOk').observe('click',function(event){ 
      if(($('newEntryTitleBox').value !== "Type your new task name here")&&($('newEntryTitleBox').value !== "")){
        Scraplr.UI.postNewEntry();
      }
    // end observe click
    });
    $('newEntryCancel').observe('click',function(event){
      Scraplr.UI.hideNewEntryDialog();
    // end observe click
    });
    var objTaskTitleHotKey = new HotKey('esc',function(event){
        if(Scraplr.UI.boolNewEntryDialogIsVisible){
          Scraplr.UI.hideNewEntryDialog();
        }
  	}); 
  	Scraplr.InputMask.setupInputMasks();          
  },
  postNewEntry: function (){      
    var arrTags = [];
    arrTags.clear();
    var arrSourceTags = $$('li.new-entry-box');
    if(arrSourceTags.length > 0){
      for (i=0; i<arrSourceTags.length; i++) {                           
        var strTag = arrSourceTags[i].down('span').innerHTML.split('<');              
          arrTags.push(strTag[0]);
      } 
    }
    var strUserId = Scraplr.Utilities.getUserId();
    var strTags = arrTags.join(';');
    
    if(arrTags.length == 0){
      strTags = null;
    }     
    
    var arrMeans = [];                 
    $$('li.meanNew').each(function(obj){
      var objCheckBoxMean = obj.down('span.meanEnabled');
        if(!objCheckBoxMean.hasClassName('hidden')){
           var strMean = objCheckBoxMean.previous(0).innerHTML;
           arrMeans.push(strMean);
        }
    });
    var strMeans = arrMeans.join(';');    
    
    var arrShareTo = []; 
    $$('li.shareNew').each(function(obj){
      var objCheckBoxMean = obj.down('span.meanEnabled');
        if(!objCheckBoxMean.hasClassName('hidden')){
           var strShare = objCheckBoxMean.identify();
           arrShareTo.push(strShare);
        }
    });
    
    var strShares = arrShareTo.join(';');    
    
    $('taskReminderAt').value= $('newReminderDateTime').innerHTML;    
    $('task_task_bin_id').value = Scraplr.TaskBins.strActiveTaskBinId;
    $('task_title').value =  $('newEntryTitleBox').value;
    $('task_note').value = $('newItemNote').value;
    $('task_due_at').value = $('taskDueAt').value;
    $('task_reminder_at').value = $('taskReminderAt').value;
    $('task_reminder_mean').value = strMeans;
    $('task_repeat_loop').value = $('recurringTimes').value; 
    $('task_repeat_date').value = $('newRecurringTimeValue').value; 
    $('task_share_mean').value = strShares; 
    $('task_tag').value = strTags;
    $('taskteammate_id').value = '';

    arrTags.clear();
    arrMeans.clear();
    arrShareTo.clear();
    
    strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/save_task/';
    Scraplr.Utilities.caramelizeScrap(strUrl, false, false, 'formNewEntry', function (){
       $('newEntrySpinner').removeClassName('hidden');       
    }, function (){       
        $('newEntrySpinner').addClassName('hidden');
        Scraplr.UI.hideNewEntryDialog();
         
        var newEntry = Scraplr.Utilities.objCaramelizedHtml;
        var arrExistingTaskItems = $('taskPaperWrapper').childElements();
        var intExistingTaskItems = arrExistingTaskItems.length;
        if (intExistingTaskItems >0){ 
          var strFirstTaskItem = arrExistingTaskItems.first().identify();
          $(strFirstTaskItem).insert({
             before: newEntry
          });
          arrExistingTaskItems = $('taskPaperWrapper').childElements();
          strFirstTaskItem = arrExistingTaskItems.first().identify();
          Scraplr.UI.arrSelectedTask.push(arrExistingTaskItems.first()); 
          Scraplr.TaskPaper.countTaskItem();
                                                               
        } else if (intExistingTaskItems == 0){   
          $('noTask').hide();
          $('taskPaperWrapper').update(newEntry); 
          $$('div.taskTitleLabel').invoke('hide');
          
        }            
        
        Scraplr.UI.initSortableTaskItems();
        Scraplr.UI.initTaskItemDraggable(); 
        //initTaskPaperFoldHandler
        var objNewTaskItem = arrExistingTaskItems.first();
        objNewTaskItem.observe('click',function(event){
          if(objNewTaskItem.hasClassName('folded')){
            Scraplr.TaskPaper.toggleSelected(objNewTaskItem, event);	
          }
        // end observe click
        });
        objNewTaskItem.observe('dblclick',function(event){        	
          Scraplr.TaskPaper.toggleFold(objNewTaskItem);        
          //Scraplr.TaskPaper.toggleEditTaskTitle(obj);
        // end observe dblclick
        });
        //initTaskCheckedToggler
        var objCheckBox = objNewTaskItem.down('div.taskItemCheck');
        objCheckBox.observe('click',function(event){
          Scraplr.TaskPaper.toggleChecked(objCheckBox, event);	
        // end observe click
        }); 
        
        //initTaskPaperTitleEdit        
        var strIds = objNewTaskItem.identify().gsub('taskItem','');
        var strTaskId = Scraplr.Utilities.getTaskIds(strIds)[3];
        var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/edit_title/'+strTaskId;
        var objTaskItemTitleEditor =  new Ajax.InPlaceEditorWithEmptyText('taskItemTitle'+strIds, strUrl,{highlightColor:'#efefef',highlightEndColor:'#efefef', fieldId:'task_title', paramName: 'task[title]', emptyText:'click to add title for this task',
        callback: function(form, value) { 
          return 'task[title]=' + encodeURIComponent(value);
        },
        onComplete: function (response){
          var strResponse = response.responseText;
          var strResponseValue = strResponse.split(';'); 
          $('taskItemTitle'+strIds).update(strResponseValue[0]);
          $('taskItemTitleLabel'+strIds).update($('taskItemTitle'+strIds).innerHTML);
          if(objTaskItem.hasClassName('folded')){
             $('taskItemTitle'+strIds).hide();
          }
          strResponseValue.clear();
        }
        });
        $('taskItemTitle'+strIds).hide();
        $('taskItemTitleLabel'+strIds).show();
        
        Scraplr.UI.initTaskBinNumBadge();
        Scraplr.TaskPaper.countTaskItem();
        if (Scraplr.Prefs.boolShowTips){
          Scraplr.UI.initToolTips();
        } 
        
        Scraplr.TaskPaper.loadTaskTags(strUserId, strTaskBinId);   
    });
  }, 
  hideNewEntryDialog: function (){
    $('newTaskShareSelector').hide();
    $('newDueDateSelector').hide();     
    $('reminderSelectorBoxNew').hide();
    $('newRecurringStartDateSelector').hide(); 
    var isInLessState = $('newEntryDialog').hasClassName('newEntryDialogLess');
    var isInMoreState = $('newEntryDialog').hasClassName('newEntryDialogMore');
    var intDialogHeight = 0;
    if(isInLessState){
        intDialogHeight = 145;
    }else if(isInMoreState){
       intDialogHeight = 380;
    }
    Scraplr.UI.toggleDialog('newEntryDialog','hide', function (){
      Scraplr.UI.boolNewEntryDialogIsVisible = false; 
      $('newEntryDialogOverlay').addClassName('hidden');
    },intDialogHeight);
  },
  openNewEntryDialog: function (){
    $('newEntryDialogOverlay').removeClassName('hidden');
    var isInLessState = $('newEntryDialog').hasClassName('newEntryDialogLess');
    var isInMoreState = $('newEntryDialog').hasClassName('newEntryDialogMore');
    var intDialogHeight = 0;
    if(isInLessState){
        intDialogHeight = 145;
    }else if(isInMoreState){
       intDialogHeight = 380;
    }         
    $$('li.new-entry-box').invoke('remove');
    $('newItemNote').value='';
    Scraplr.UI.toggleDialog('newEntryDialog','show', function (){
      Scraplr.UI.boolNewEntryDialogIsVisible = true;
      // setup datetime picker
      $('newDueDate').value = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay; 
      if(Scraplr.Utilities.timeMinutes < 10){
        var strMinute = '0'+Scraplr.Utilities.timeMinutes;
      }else{
        var strMinute = Scraplr.Utilities.timeMinutes;
      }
      if(Scraplr.Utilities.timeHours<10){
        var strHour = '0'+Scraplr.Utilities.timeHours;
      }else{
        var strHour = Scraplr.Utilities.timeHours;
      }
      $('newDueTime').value = strHour+':'+strMinute;
      $('newDuePicker').innerHTML = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+strHour+':'+strMinute; 
      $('taskDueAt').value = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+strHour+':'+strMinute; 
      console.log('Scraplr.UI.openNewEntryDialog execution finished');       
    },intDialogHeight);
    $('newEntryTitleBox').style.color = Scraplr.UI.strNewEntryTitleBoxInactiveColor ;
    $('newEntryTitleBox').value = "Type your new task name here";
    $('newEntryTitleBox').focus();    
  },
  initTaskCheckedToggler: function (){
    // Task Item
    $$('div.taskItemCheck').each(function(obj){
      obj.observe('click',function(event){
        Scraplr.TaskPaper.toggleChecked(obj, event);	
      // end observe click
      });           
    });
  },
  initDueDatePicker: function (strTargetIds){
    var arrDue = ($('dueDateBox'+strTargetIds).innerHTML).split(' ');
    $('taskItemDue'+strTargetIds).value = $('dueDateBox'+strTargetIds).innerHTML; 
    var strReminderDateTimeSource = $('taskItemDue'+strTargetIds).value ;
    $('dueDate'+strTargetIds).value = arrDue[0];
    
      $('dueDateBox'+strTargetIds).observe('click',function(event){         
        $('reminderSelectorBox'+strTargetIds).hide();
        $('shareSelectorBox'+strTargetIds).hide();
        $('dueDateSelector'+strTargetIds).toggle();
        if(Scraplr.Utilities.timeMinutes < 10){
          var strMinute = '0'+Scraplr.Utilities.timeMinutes;
        }else{
          var strMinute = Scraplr.Utilities.timeMinutes;
        }
        if(Scraplr.Utilities.timeHours<10){
          var strHour = '0'+Scraplr.Utilities.timeHours;
        }else{
          var strHour = Scraplr.Utilities.timeHours;
        }
        $('dueTime'+strTargetIds).value = strHour+':'+strMinute;	
        $('dueTime'+strTargetIds).focus();
      // end observe click
      });           
      
      $('dueDateBox'+strTargetIds).observe('dblclick',function(event){
        event.stop();
      });
   
      dueCal = new ScraplrUI.Calendar($('dueDateSelector'+strTargetIds).identify(), {
        format: Scraplr.Utilities.strDateFormat
      }); 
      
      
      dueCal.observe('click',function(e) {   
        var strDueTime = $('dueTime'+strTargetIds).value;        
        if((strDueTime != '') && (/^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$/).test(strDueTime)){
          $('dueDateBox'+strTargetIds).innerHTML = e.memo.formattedDate +' '+strDueTime;
          $('dueDate'+strTargetIds).value = e.memo.formattedDate; 
          $('taskItemDue'+strTargetIds).value = e.memo.formattedDate +' '+strDueTime;
          Scraplr.TaskPaper.setReminder('2 Hours before', $('reminderSelector'+strTargetIds), $('taskItemDue'+strTargetIds).value);
          Scraplr.TaskPaper.editDue(strTargetIds);
        }else{
          Scraplr.UI.showDialog ('alert', 'Time format is invalid', 'Please use one of the following format:<br/> hh:mm or hh:mm am/pm',function (){}, function (){
            $('dueTime'+strTargetIds).value ="";
            $('dueTime'+strTargetIds).focus();
          },false);
        }        
      });
      
      dueCal.observe('dblclick',function(event){
        event.stop();
      }); 
      
      $('dueTime'+strTargetIds).observe('keyup',function(event){
        var strDueTime = $('dueTime'+strTargetIds).value;
        if((strDueTime != '') && (/^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$/).test(strDueTime)){	
          $('dueDateBox'+strTargetIds).innerHTML = $('dueDate'+strTargetIds).value + ' '+$('dueTime'+strTargetIds).value;
          $('taskItemDue'+strTargetIds).value = $('dueDate'+strTargetIds).value + ' '+$('dueTime'+strTargetIds).value;

          Scraplr.TaskPaper.setReminder(strDueTime, $('reminderSelector'+strTargetIds), $('taskItemDue'+strTargetIds).value);
        }
      });
      
      new HotKey('enter',function(e){
        var strDueTime = $('dueTime'+strTargetIds).value;
        if((strDueTime != '') && (/^((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$/).test(strDueTime)){
          $('dueDateBox'+strTargetIds).innerHTML = $('dueDate'+strTargetIds).value + ' '+$('dueTime'+strTargetIds).value;
          $('taskItemDue'+strTargetIds).value = $('dueDate'+strTargetIds).value + ' '+$('dueTime'+strTargetIds).value;
          Scraplr.TaskPaper.setReminder('2 Hours before', $('reminderSelector'+strTargetIds), $('taskItemDue'+strTargetIds).value);
          Scraplr.TaskPaper.editDue(strTargetIds);          
        }
    	},{element:$('dueTime'+strTargetIds).identify()});
      Scraplr.InputMask.setupInputMasks();  
  },
  initTaskItemShareMeanPicker: function (strTargetIds){
      $('taskItemShareSelectors'+strTargetIds).observe('click',function(event){
  	    $('dueDateSelector'+strTargetIds).hide();
        $('reminderSelectorBox'+strTargetIds).hide();
        $('shareSelectorBox'+strTargetIds).toggle(); 
      // end observe click
      });
      $('taskItemShareSelectors'+strTargetIds).observe('dblclick',function(event){
        event.stop();
      });                 
  },
  initTaksItemShareMeanCheckList: function (strTargetIds){
    $$('li.taskItemShareMean').each(function(obj){
      var objCheckBoxMean = obj.down('span.shareEnabled');
      objCheckBoxMean.addClassName('hidden');     
      obj.observe('dblclick',function(event){
        event.stop();
      });          
    });    
  },  
  initReminderMeanPicker: function (strTargetIds){
    
    
    $('reminderSelector'+strTargetIds).innerHTML = Scraplr.Utilities.dateYear + '-' + Scraplr.Utilities.dateMonth + '-' + Scraplr.Utilities.dateDay+' '+Scraplr.Utilities.timeHours+':'+Scraplr.Utilities.timeMinutes; 
      $('reminderValue'+strTargetIds).value = '2 Hours before';
      $('reminderSelector'+strTargetIds).observe('click',function(event){
  	    $('dueDateSelector'+strTargetIds).hide();
  	    $('shareSelectorBox'+strTargetIds).hide();
        $('reminderSelectorBox'+strTargetIds).toggle(); 
        try{
          $('reminderSelectorBox'+strTargetIds).down('input.reminderValueBox').focus();
        } catch(ex){
          log: Prototype.emptyFunction;
        }
      // end observe click
      });
      $('reminderSelector'+strTargetIds).observe('dblclick',function(event){
        event.stop();
      });      
      

      Scraplr.Utilities.setHotKey('enter', function(){ 
        if(!Scraplr.UI.boolNewEntryDialogIsVisible){       
          if($('reminderValue'+strTargetIds).value !== ''){ 
            // todo -> check validity, submit value..
            $('reminderSelectorBox'+strTargetIds).hide();
          }
        }      
      },$('reminderValue'+strTargetIds).identify());

      $('reminderValue'+strTargetIds).observe('keyup',function(event){	
        var strReminderValue = $('reminderValue'+strTargetIds).value;
        var strReminderDateTimeSource = $('taskItemDue'+strTargetIds).value ;
        Scraplr.TaskPaper.setReminder(strReminderValue, $('reminderSelector'+strTargetIds), strReminderDateTimeSource);
      });           
  },
  initReminderMeanCheckList: function (strTargetIds){
    $$('li.mean'+strTargetIds).each(function(obj){
      var objCheckBoxMean = obj.down('span.meanEnabled');
      //objCheckBoxMean.addClassName('hidden');
      obj.observe('click',function(event){	
        if((objCheckBoxMean.hasClassName('hidden'))&&(!obj.hasClassName('reminderNA'))){
           objCheckBoxMean.removeClassName('hidden');
           $('reminderBy').update(Scraplr.UI.dumpReminderMeanToString());
        }else if((!objCheckBoxMean.hasClassName('hidden'))&&(!obj.hasClassName('reminderNA'))){
           objCheckBoxMean.addClassName('hidden');
           $('reminderBy').update(Scraplr.UI.dumpReminderMeanToString());
        }
      //obj.up('div.reminderSelectBox').identify().gsub('reminderValue_','');
      // end observe click
      });
      obj.observe('dblclick',function(event){
        event.stop();
      });           
    });
    
  },
  dumpReminderMeanToString: function (){
    var arrMeans = [];
    $$('li.meanNew').each(function(obj){
      var objCheckBoxMean = obj.down('span.meanEnabled');
        if(!objCheckBoxMean.hasClassName('hidden')){
           var strMean = objCheckBoxMean.previous(0).innerHTML;
           arrMeans.push(strMean);
        }
    });
    var strMeans = arrMeans.join(',');
    arrMeans.clear();
    return strMeans;     
  },
  initTagsEntryBox: function (strTargetIds){
      if(strTargetIds!='New'){
        var tagListBox = new ScraplrUI.AutoComplete('tagListBox'+strTargetIds, {max:{selection: 4, selected:5}});
      }else if(strTargetIds=='New'){
        var tagListBox = new ScraplrUI.AutoComplete('tagListBox'+strTargetIds, {max:{selection: 4, selected:5}, className:'new-entry'});
      } 
      
      tagListBox.observe('input:empty',           function(event) {event.memo.autocomplete.showMessage("Type to include tag(s) for this task");});
      tagListBox.observe('selection:max_reached', function(event) {
        Scraplr.UI.showDialog ('alert', 'We think five tags for a task might be enough :)', 'Many tags for a task item would be confusing anyway..',function (){}, function (){},false);        
      });
      tagListBox.observe('selection:empty',       function(event) {event.memo.autocomplete.showMessage("No tags match, type then press enter to create new tag");});       
      tagListBox.observe('element:added', function(event){ 
        if(!Scraplr.UI.boolNewEntryDialogIsVisible){ 
          Scraplr.TaskPaper.addTaskTag('tagListBox'+strTargetIds, event.memo.text);
          var strTagToAdd = $('taskItem'+strTargetIds).down('div.taskItemTags').innerHTML;
          if ((strTagToAdd =='0')||(strTagToAdd =='')){
            strTagToAdd = '';
          }else{
            strTagToAdd = strTagToAdd+';';
          }
          $('taskItem'+strTargetIds).down('div.taskItemTags').update(strTagToAdd+event.memo.text);
        }        
      });
      
      var strUrl = '/'+Scraplr.Utilities.getUserName()+'/response/get_tags/';
      Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
      },function(){
        var strResponse = Scraplr.Utilities.objCaramelizedHtml;
        var strResponseValue = strResponse.split(';');
        var arrTaskTags = strResponseValue[0];
        tagListBox.setAutocompleteList(eval(arrTaskTags));        
      });      
      
   
        
        var obj = $('tagListBox'+strTargetIds);
        obj.value = "tags";
        obj.setStyle('color:#aaa !important;');
        obj.observe('click',function(event){
          obj.value = "";
          obj.setStyle('color:#555 !important;');  	
        // end observe click
        });
        obj.observe('dblclick',function(event){
          event.stop();
        });        
        obj.observe('blur',function(event){ 
          if(obj.value === ""){
            obj.value = "tags";
            obj.setStyle('color:#aaa !important;');           
          } 
        // end observe click
        });           
        
  },
  initShareMeanCheckList: function (){
    $$('li.taskShareMean').each(function(obj){
      var objCheckBoxMean = obj.down('span.meanEnabled');
      //objCheckBoxMean.addClassName('hidden');
      obj.observe('click',function(event){	
        if(objCheckBoxMean.hasClassName('hidden')){
           objCheckBoxMean.removeClassName('hidden');
        }else if(!objCheckBoxMean.hasClassName('hidden')){
           objCheckBoxMean.addClassName('hidden');
        }
      // end observe click
      });           
    });    
  },
  initPreferencesPane: function (){
    var strTimeZone = -Scraplr.Utilities.dateDate.getTimezoneOffset()/60;
    /*var strUrl = '/save_preference?timezone='+strTimeZone;
                                         
      Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
        //onCreateXHR
      },function(){
        
      });*/    
    
    console.log('user time zone:', -Scraplr.Utilities.dateDate.getTimezoneOffset()/60);
    $('userPreferences').setStyle('top:-298px;');
    new ScraplrTabs('preferencesTab', {defaultPanel: 'profile'});
    if(Scraplr.Prefs.boolIsPlusMember){
        $('phoneConnectEnabled').show();
        $('phoneConnectDisabled').hide();
    }else if(!Scraplr.Prefs.boolIsPlusMember){
        $('phoneConnectDisabled').show();
        $('phoneConnectEnabled').hide();
    }
    $('preferencesOk').observe('click',function(event){
      var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/save_preference/';
      Scraplr.Utilities.caramelizeScrap(strUrl, true, false, 'formPreference', function (){
          $('preferencesSpinner').show();
      },function(){
        Scraplr.UI.toggleDialog('userPreferences','hide', function (){
          $('preferencesSpinner').hide();
          Scraplr.UI.boolPreferencesIsVisible = false;
          Scraplr.UI.showDialog ('alert', 'Your preferences has been saved', '',function (){}, function (){},true);
        },298);

      });    
    // end observe click
    });
    $('preferencesCancel').observe('click',function(event){
      Scraplr.UI.toggleDialog('userPreferences','hide', function (){
        Scraplr.UI.boolPreferencesIsVisible = false;
      },298);	
    // end observe click
    });
    
      new HotKey('esc',function(event){
        if(Scraplr.UI.boolPreferencesIsVisible){
          Scraplr.UI.toggleDialog('userPreferences','hide', function (){
            Scraplr.UI.boolPreferencesIsVisible = false;
          },298);
  	    }
    	});
    
    if($('twitConnect')!= null){
      $('twitConnect').observe('click',function(event){	
  	    var strUrl = '/twitter_connect';
  	    Scraplr.Utilities.openWindow(strUrl, 800, 400) ;
      // end observe click
      });      
    }else{
      $('disconnectTwitterBt').observe('click',function(event){ 
        var strPreferencesUserTwitName = $('preferencesUserTwitName').innerHTML;
        Scraplr.UI.showDialog ('confirm', 'Are you sure want to disconnect Twitter account "'+strPreferencesUserTwitName+'" from Scraplr?','',function (){
        }, function (){  
           var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/disconnect_twitter/';
           Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
           },function(){           
             var strUrl = 'request/twitter_info';
             Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
               //Element.show('activityIndicator');
             },function(){
               var strHtml = Scraplr.Utilities.objCaramelizedHtml;
                $('twitter').update(strHtml);                  
             });                             
           });           
        },false);	
      // end observe click
      });
    }
    
    if($('fbConnectBt')!=null){
      $('fbConnectBt').observe('click',function(event){
        	Scraplr.FbConnect.ShowAppPermissionDialog();
      // end observe click
      });      
    }else{
      $('disconnectFacebookBt').observe('click',function(event){ 
        var strPreferencesUserFBName = $('preferencesUserFBName').innerHTML;
        Scraplr.UI.showDialog ('confirm', 'Are you sure want to disconnect Facebook account "'+strPreferencesUserFBName+'" from Scraplr?','',function (){
        }, function (){  
           console.log('do function to disconnect');
           var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/disconnect_facebook/';
           Scraplr.Utilities.caramelizeScrap(strUrl, true, false, null, function (){
           },function(){           
             var strUrl = 'request/facebook_info';
             Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
               //Element.show('activityIndicator');
             },function(){
               var strHtml = Scraplr.Utilities.objCaramelizedHtml;
                $('facebook').update(strHtml);                  
             });                             
           });             
        },false);         
      // end observe click
      });
    }    
            
  },  
  initToolTips: function (){
    $$('div.taskItemDragHandle').each(function(obj){
      Scraplr.UI.setupToolTip(obj, "Double click to unfold or fold<br/><br/>Drag upwards or downwards to reorder.<br/><br/>Drag towards container tab to move task to another container", 200, true);
      obj.tip = Scraplr.UI.taskItemToolTip; 		           
    });
  },
  setupToolTip: function (obj, strTip, intWidth, boolHookMouse){
    Scraplr.UI.taskItemToolTip = new Tip(obj.identify(), strTip, {
			delay: 0.1,
			border: 6,
			radius: 6,
			style: 'darkgrey',
			stem: 'bottomMiddle',
			hook: { mouse: boolHookMouse, tip: 'bottomMiddle', target: 'topMiddle'},
			offset: { x: 0, y: 0 },
			width: intWidth
		});
  }, 
  initTagHudButtons: function (){
    Scraplr.UI.setupToolTip($('btHudTag'), 'Show Task Tag list to add more predefined tags or create new tag', 200, false);
    Scraplr.UI.setupToolTip($('btHudTeam'), 'Show TaskMate list to add more task mate or add new task mate', 200, false);
    Scraplr.UI.setupToolTip($('btHudTaskFlow'), 'Show Task Router to help you place task(s)', 200, false);
    
    $('btHudTag').observe('click',function(event){
      Scraplr.Utilities.intTopScrollOffsets =  document.viewport.getScrollOffsets().top; 
      if(!Scraplr.Hud.boolTagHudIsVisible){
        Scraplr.UI.setTagHudContent();
      }else{
        Scraplr.Hud.objTagHud.close();
      }
    });
    
    $('btHudTeam').observe('click',function(event){	
      Scraplr.Utilities.intTopScrollOffsets =  document.viewport.getScrollOffsets().top; 
      if(!Scraplr.Hud.boolMateHudIsVisible){
        Scraplr.UI.setMateHudContent();
      }else{
        Scraplr.Hud.objMateHud.close();
      }
    });
    
    $('btHudTaskFlow').observe('click',function(event){
      	
      Scraplr.Utilities.intTopScrollOffsets =  document.viewport.getScrollOffsets().top; 
      if(!Scraplr.Hud.boolRouterHudIsVisible){
        Scraplr.UI.setRouterHudContent();
      }else{
        Scraplr.Hud.objRouterHud.close();
      }      
    });
  },
  setTagHudContent: function (){
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/response/task_tag/';
    Scraplr.Hud.objTagHud.show().setAjaxContent(strUrl, {
      method: "GET", 
      onCreate: function() {
        this.setContent('<div class="spinnerHud">Loading</div>');   
      },
      onComplete: function (response){
        var strResponse = response.responseText;
        if (strResponse.startsWith('<div id="tagListContainer">')){
          Scraplr.Hud.boolTagHudIsVisible=true;
          $('tag_name').value = 'Tag Name';
          Scraplr.UI.initTextValueSwitcher($('tag_name'), 'Tag Name', function (){}, true);
          Scraplr.Hud.initTagHudListItem();
          new HotKey('enter',function(e){
            Scraplr.Hud.addTag();
        	},{element:$('tag_name').identify()});
      
          $('addNewTagButton').observe('click',function(event){ 
            Scraplr.Hud.addTag(); 
          // end observe click
          });
        }
      }
    });    
  },
  setMateHudContent: function (){
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/response/task_teammate/';
    Scraplr.Hud.objMateHud.show().setAjaxContent(strUrl, {
      method: "GET", 
      onCreate: function() {   
        this.setContent('<div class="spinnerHud">Loading</div>');   
      },
      onComplete: function (){ 
        Scraplr.Hud.boolMateHudIsVisible=true;
        $('teammate_name').value = 'Name';
        $('teammate_email').value = 'Email';
        Scraplr.UI.initTextValueSwitcher($('teammate_name'), 'Name', function (){$('teammate_email').focus();}, true);
        Scraplr.UI.initTextValueSwitcher($('teammate_email'), 'Email', function (){}, false);          
        $$('li.taskMateListItem').each(function(obj){      
          new Draggable(obj, { 
            superghosting:true,   
            onStart: function (item){
              console.log('startDragging',item.element.identify()); 
              Scraplr.UI.isDragging = true;
              item.element.addClassName('isDragged');
            },
            onEnd: function (item){ 
                Scraplr.UI.isDragging = false;
                item.element.removeClassName('isDragged');           
            },
            starteffect: function (){},
            endeffect: function (){}        
          });
        });            
        
        var i = 1;
        $$('li.taskMateListItem').each(function(obj){
          if (i%2 == 0){
            obj.addClassName('alternateTaskMateRow');
          }
          i++;
        }); 
        
        new HotKey('enter',function(e){
          Scraplr.Hud.addMate();
      	},{element:$('teammate_email').identify()});
      	
        $('addNewTaskMateButton').observe('click',function(event){ 
          Scraplr.Hud.addMate(); 
        // end observe click
        });          
      }
    });    
  },
  setRouterHudContent: function (){
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/response/task_router/';
    Scraplr.Hud.objRouterHud.show().setAjaxContent(strUrl, {
      method: "GET", 
      onCreate: function() {   
        this.setContent('<div class="spinnerHud">Loading</div>');   
      },
      onComplete: function (){
        Scraplr.Hud.boolRouterHudIsVisible=true; 
        $('taskRouterLaterButton').observe('click',function(event){	
          Scraplr.TaskRouter.routeTask('5');
        // end observe click
        });
        $('taskRouterRecyclerButton').observe('click',function(event){ 
          Scraplr.TaskRouter.routeTask('7'); 
        // end observe click
        });
        $('taskRouterCollabButton').observe('click',function(event){
          if(!Scraplr.Hud.boolMateHudIsVisible){
            Scraplr.UI.setMateHudContent();
          }	
        // end observe click
        }); 
        $('taskRouterScheduleButton').observe('click',function(event){
          Scraplr.TaskRouter.routeTask('3');	
        // end observe click
        });
        $('taskRouterProjectButton').observe('click',function(event){
          Scraplr.UI.showDialog ('alert', 'Sorry, project container won\'t be available until beta release', '',function (){}, function (){},true);	
        // end observe click
        });
        $('taskRouterNextButton').observe('click',function(event){
          Scraplr.TaskRouter.routeTask('2');	
        // end observe click
        });
        // router setup
      }
    });    
  },
  hideAutoCompleteResultWrapper: function (){ 
    if(Scraplr.UADetector.Browser === 'IE'){
      try{
        $$('div.ScraplrUI-widget-dropdown').invoke('hide');  
      }catch(ex){
       log: Prototype.emptyFunction; 
      }
    }else{
      log: Prototype.emptyFunction;
    }
  },
  showDialog: function (strDialogType, strMessage, strSubMessage, cancelCallback, okCallback, boolTimerIsEnabled){
    
    $('dialogMessage').innerHTML = strMessage; 
    $('dialogSubMessage').innerHTML = strSubMessage;
       
    if(strDialogType === 'alert'){
      $('dialogCancel').hide();
      if($('dialogIcon').hasClassName('dialogQuestionIcon')){
        $('dialogIcon').removeClassName('dialogQuestionIcon');
        $('dialogIcon').addClassName('dialogInfoIcon');        
      }      
    }else{
      $('dialogCancel').show();
      if($('dialogIcon').hasClassName('dialogInfoIcon')){
        $('dialogIcon').removeClassName('dialogInfoIcon');
        $('dialogIcon').addClassName('dialogQuestionIcon');
      }
    }        
    if (!Scraplr.UI.boolDialogIsVisible){
      Scraplr.UI.toggleDialog('userDialog','show', function (){
        Scraplr.UI.boolDialogIsVisible = true;
      },180);
    }    
    $('dialogOk').observe('click',function(event){      
      if(strDialogType === 'alert'){
        Scraplr.UI.toggleDialog('userDialog','hide', function (){
          Scraplr.UI.boolDialogIsVisible = false;
          $('dialogOk').stopObserving(); 
          $('dialogCancel').stopObserving();
        },180);
      }else{
        okCallback();
        Scraplr.UI.toggleDialog('userDialog','hide', function (){
          Scraplr.UI.boolDialogIsVisible = false;
          $('dialogOk').stopObserving(); 
          $('dialogCancel').stopObserving();
        },180);
      }	
    // end observe click
    });    
    $('dialogCancel').observe('click',function(event){
      cancelCallback(); 
      Scraplr.UI.toggleDialog('userDialog','hide', function (){
        Scraplr.UI.boolDialogIsVisible = false;
        $('dialogOk').stopObserving(); 
        $('dialogCancel').stopObserving(); 
      },180);
    // end observe click
    });
    new HotKey('enter',function(event){
      if(Scraplr.UI.boolDialogIsVisible){  
        if(strDialogType === 'alert'){
          Scraplr.UI.toggleDialog('userDialog','hide', function (){
            Scraplr.UI.boolDialogIsVisible = false;
            $('dialogOk').stopObserving(); 
            $('dialogCancel').stopObserving();
          },180);
        }else{
          okCallback();
          Scraplr.UI.toggleDialog('userDialog','hide', function (){
            Scraplr.UI.boolDialogIsVisible = false;
            $('dialogOk').stopObserving(); 
            $('dialogCancel').stopObserving();
          },180);
        }
    	}
  	});
    new HotKey('esc',function(event){
      if(Scraplr.UI.boolDialogIsVisible){
        cancelCallback(); 
        Scraplr.UI.toggleDialog('userDialog','hide', function (){
          Scraplr.UI.boolDialogIsVisible = false; 
          $('dialogOk').stopObserving(); 
          $('dialogCancel').stopObserving();
        },180);
      }
  	});    

    if((strDialogType == 'alert')&&(boolTimerIsEnabled)){
      setTimeout( "Scraplr.UI.hideDialog('userDialog')", 5000 );
    }
  },
  toggleDialog: function (strDialogId, strToggleState, afterFinishCallback, intHeight){
    if(!Scraplr.UI.boolDialogIsSliding){
      Scraplr.UI.boolDialogIsSliding = true;
      var intTopStep = 0;
      if(strToggleState === 'show'){
        intTopStep = intHeight;
      }else if(strToggleState === 'hide'){
        intTopStep = -intHeight;
      }
      new Effect.Move($(strDialogId).identify(), { x: 0, y: intTopStep, duration: 0.25, fps: 100, transition: Effect.Transitions.easeInOutSine,
        afterFinish: function() {
          Scraplr.UI.boolDialogIsSliding = false;
          afterFinishCallback();
        }
      });  
    }
  },
  hideDialog: function (element){ 
    Scraplr.UI.toggleDialog(element,'hide', function (){
      Scraplr.UI.boolDialogIsVisible = false;
      $('dialogOk').stopObserving(); 
      $('dialogCancel').stopObserving();       
    },180);
  },
  filterTaskByTag: function (objSourceTagElement,objEvent){ 
    var arrSelectedTags = [];
    var objTagStringContainer = objSourceTagElement.down('span.tagTokenSpan');
    var strTag = objTagStringContainer.innerHTML.toLowerCase();
    
    if(Scraplr.Utilities.isControlKeyPressed(objEvent)){ 
      if(strTag != 'all'){          
        $$('li.tagTokenCap')[0].removeClassName('activeTagCap');
        $$('li.tagTokenCap')[0].down('span.tagTokenSpan').removeClassName('activeTagSpan');        
        if(!objSourceTagElement.hasClassName('activeTagCap')){
          objSourceTagElement.addClassName('activeTagCap');
          objTagStringContainer.addClassName('activeTagSpan');
          arrSelectedTags.push(strTag);          
        }else if(objSourceTagElement.hasClassName('activeTagCap')){
          objSourceTagElement.removeClassName('activeTagCap');
          objTagStringContainer.removeClassName('activeTagSpan');
          arrSelectedTags.pull(strTag);
        }
        Scraplr.Utilities.displayQSSearchResults(Scraplr.Utilities.getSearchScores(strTag),true);
      }
    }else if(!Scraplr.Utilities.isControlKeyPressed(objEvent)){
      arrSelectedTags.clear(); 
      if(!objSourceTagElement.hasClassName('activeTagCap')){
        $$('li.tagTokenCap').each(function(obj){        
          obj.removeClassName('activeTagCap');           
          obj.down('span.tagTokenSpan').removeClassName('activeTagSpan');
        });
        objSourceTagElement.addClassName('activeTagCap');
        objTagStringContainer.addClassName('activeTagSpan');        
      }else if(objSourceTagElement.hasClassName('activeTagCap')){ 
        var intSelectedTagNum = $$('li.activeTagCap').length;
        if(intSelectedTagNum>1){
          $$('li.tagTokenCap').each(function(obj){        
            obj.removeClassName('activeTagCap');           
            obj.down('span.tagTokenSpan').removeClassName('activeTagSpan');
          });
          objSourceTagElement.addClassName('activeTagCap');
          objTagStringContainer.addClassName('activeTagSpan');          
        } else{
          objSourceTagElement.removeClassName('activeTagCap');
          objTagStringContainer.removeClassName('activeTagSpan');
          $$('li.tagTokenCap').each(function(obj){        
            obj.removeClassName('activeTagCap');           
            obj.down('span.tagTokenSpan').removeClassName('activeTagSpan');
          });        
          $$('li.tagTokenCap')[0].addClassName('activeTagCap');
          $$('li.tagTokenCap')[0].down('span.tagTokenSpan').addClassName('activeTagSpan');        
          strTag = 'all';
        }
      }
    
      if(strTag != 'all'){
        Scraplr.Utilities.displayQSSearchResults(Scraplr.Utilities.getSearchScores(strTag),false);
      }else if(strTag == 'all'){
        Scraplr.Utilities.arrQSSearchObj.invoke('show');
      }
    }
  },
  setTagBar: function (){  
      $('taskTagsWrapper').show();
      var intTagBarWidth = 35;      
      $$('li.tagTokenCap').each(function(objTag){         
        var intTagTokenWidth = objTag.offsetWidth;
        intTagBarWidth += intTagTokenWidth;           
      }); 
      
      var intTagBarContainerWidth = parseInt(Scraplr.UI.viewportwidth - $('searchHudBox').offsetWidth,10) - 35;
      $('tagsBarContainer').setStyle('width:'+intTagBarContainerWidth+'px;'); 
      $('tagsBar').setStyle('width:'+intTagBarWidth+'px;');
      $('tagsBar').setStyle('left:0;');
      Scraplr.UI.boolSlideLeftTagIsEnabled = false;
      Scraplr.UI.boolSlideRightTagIsEnabled = true;

      if(intTagBarWidth>intTagBarContainerWidth){
        $('tagScrollBtRight').removeClassName('hidden');
        $('tagScrollBtLeft').removeClassName('hidden');      
        $('tagScrollBtLeft').observe('click',function(event){
          if((Scraplr.UI.boolSlideLeftTagIsEnabled)&&(!Scraplr.UI.boolTagBarIsSliding)){
            Scraplr.UI.boolTagBarIsSliding = true;
            Scraplr.UI.slideTagBar('Left', function (){
              Scraplr.UI.boolSlideLeftTagIsEnabled = false;
              Scraplr.UI.boolSlideRightTagIsEnabled = true;
              Scraplr.UI.boolTagBarIsSliding = false;
            });      
          }
        // end observe click
        });

        $('tagScrollBtRight').observe('click',function(event){
          if((Scraplr.UI.boolSlideRightTagIsEnabled)&&(!Scraplr.UI.boolTagBarIsSliding)){
            Scraplr.UI.boolTagBarIsSliding = true;
            Scraplr.UI.slideTagBar('Right', function (){
              Scraplr.UI.boolSlideRightTagIsEnabled = false;
              Scraplr.UI.boolSlideLeftTagIsEnabled = true;
              Scraplr.UI.boolTagBarIsSliding = false;
            });      
          }
        // end observe click
        });            
      }else{
        $('tagScrollBtRight').addClassName('hidden');
        $('tagScrollBtLeft').addClassName('hidden');      
      }
   
  },
  slideTagBar: function (strDirection, callBackAfterFinish){   
    var intTagBarWidth = 0;
    $$('li.tagTokenCap').each(function(obj){
      intTagBarWidth += obj.offsetWidth;
    });

    var intTagBarContainerWidth = Scraplr.UI.viewportwidth - $('searchHudBox').offsetWidth - 40;
    var intScrollSize = intTagBarWidth - intTagBarContainerWidth ;
    
      if (strDirection == 'Left'){
        var intScroll =  intScrollSize;
      } else if(strDirection == 'Right'){
        var intScroll = -intScrollSize;
      }
      new Effect.Move($('tagsBar'), { 
                     x: intScroll, 
                     y: 0, 
                     mode: 'relative', 
                     duration:0.5, 
                     fps: 200, 
                     transition: Effect.Transitions.easeInOutSine, 
                     afterFinish: function() {
                       callBackAfterFinish();
                     }  
      });
  }, 
  initSearchPopBox: function (){
    $('searchScopeIcon').observe('click',function(event){	
      $('searchScopeSelect').toggle();
    // end observe click
    });
    
    $$('li.searchScopeItem').each(function(obj){
        var objCheckBoxMean = obj.down('span.scopeEnabled');
        //objCheckBoxMean.addClassName('hidden');
        obj.observe('click',function(event){ 
          $$('span.searchScopeCheck').each(function(obj){
            obj.addClassName('hidden');           
          }); 
          if(objCheckBoxMean.hasClassName('hidden')){
             objCheckBoxMean.removeClassName('hidden');
          }else if(!objCheckBoxMean.hasClassName('hidden')){
             objCheckBoxMean.addClassName('hidden');
          }                               
          $('searchKeyword').focus();
        //obj.up('div.reminderSelectBox').identify().gsub('reminderValue_','');
        // end observe click
        });           
    });       

    $$('li.searchCriteriaItem').each(function(obj){
        var objCheckBoxMean = obj.down('span.scopeEnabled');
        //objCheckBoxMean.addClassName('hidden');
        obj.observe('click',function(event){ 
          $$('span.searchCriteriaCheck').each(function(obj){
            obj.addClassName('hidden');           
          }); 
          if(objCheckBoxMean.hasClassName('hidden')){
             objCheckBoxMean.removeClassName('hidden');
             var strSearchScope = obj.down('span.searchScopeLabel').innerHTML.toLowerCase(); 
             Scraplr.Utilities.strLocalSearchCriteria = strSearchScope; 
             Scraplr.Utilities.initQuicksilverSearch('searchKeyword', 'div.taskItem');
          }else if(!objCheckBoxMean.hasClassName('hidden')){
             objCheckBoxMean.addClassName('hidden');
          }
          $('searchKeyword').focus(); 
      
        //obj.up('div.reminderSelectBox').identify().gsub('reminderValue_','');
        // end observe click
        });           
    });
    
    //Scraplr.UI.initTextValueSwitcher($('searchKeyword'), 'search', function (){}, true);    
  },
  initTextValueSwitcher: function (objTextBox, strTextBoxValue, callback, boolEnableCallback){
    objTextBox.observe('keyup',function(event){
      if(boolEnableCallback){
        new HotKey('enter',function(event){
          if((objTextBox.value !== strTextBoxValue)&&(objTextBox.value !== "")){
            callback();
          }
      	});
    	}      	
      if(objTextBox.value === strTextBoxValue){
        objTextBox.value = ""; 
      }
      // FF and Safari, focused text box placed cursor at the end of the words while IE at the beginning. So, an 'OR' should work
      if((objTextBox.value.startsWith(strTextBoxValue))||(objTextBox.value.endsWith(strTextBoxValue))){
        objTextBox.value = objTextBox.value.gsub(strTextBoxValue,''); 
      }      
    });       
    objTextBox.observe('blur',function(event){	
      if(objTextBox.value === ""){     
        objTextBox.value = strTextBoxValue ;
        objTextBox.focus();
      }
    // end observe blur
    });     
    objTextBox.observe('click',function(event){	
      if(objTextBox.value === strTextBoxValue){     
        objTextBox.value = "";
      }
    // end observe focus
    });    
  },  
  initAdsSection: function (){
    /*
    if(Scraplr.Prefs.boolIsPlusMember || Scraplr.Prefs.boolIsAdmin){
      if(!$('fusionAds').hasClassName('hidden')){
        $('fusionAds').addClassName('hidden');
      }
      $('taskPaperWrapper').setStyle('top:145px;');
      $('noTask').setStyle('top:145px;');                         
    }else if(!Scraplr.Prefs.boolIsPlusMember || !Scraplr.Prefs.boolIsAdmin){
      if($('fusionAds').hasClassName('hidden')){
        $('fusionAds').removeClassName('hidden');
      }
      $('taskPaperWrapper').setStyle('top:285px;');
      $('noTask').setStyle('top:285px;');
    } */
    $('fusionAds').removeClassName('hidden');
    $('taskPaperWrapper').setStyle('top:285px;');
    $('noTask').setStyle('top:285px;');   
  }
};   

Scraplr.Prefs = {
   boolShowTips : true,
   strBackdropPath : '',
   boolIsAdmin: false,
   boolIsPlusMember : false,
   loadUserPrefs: function(strUserId) { 
     console.log('Scraplr.Prefs.loadUserPrefs(strUserId);');
     //var strUrl = 'userpref.html?strRandom='+Scraplr.Utilities.randomize()+'&strUserId='+strUserId;
     var strUrl = '/'+Scraplr.Utilities.getUserName()+'/response/preferences/'; 
     Scraplr.Utilities.caramelizeScrap(strUrl, false, true, null, function (){
       //Element.show('activityIndicator');
     },function(){
        
       //Element.hide('activityIndicator');
       var jsonObj = Scraplr.Utilities.objCaramelizedJson;
       Scraplr.Prefs.boolShowTips = jsonObj.boolShowTips;
       Scraplr.Prefs.strBackdropPath = jsonObj.strBackdropPath ;
       Scraplr.Prefs.boolIsPlusMember = jsonObj.boolIsPlusMember;
       Scraplr.UI.initPreferencesPane();
       Scraplr.UI.initAdsSection();
     });
   },
   loadAdminPrefs: function(strUserId) {
     var strUrl = '/'+Scraplr.Utilities.getUserName()+'/admin/main/preferences/'; 
     Scraplr.Utilities.caramelizeScrap(strUrl, false, true, null, function (){
     },function(){
       var jsonObj = Scraplr.Utilities.objCaramelizedJson;
       Scraplr.Prefs.boolShowTips = jsonObj.boolShowTips;
       Scraplr.Prefs.strBackdropPath = jsonObj.strBackdropPath ;
       Scraplr.Prefs.boolIsPlusMember = jsonObj.boolIsPlusMember;
       Scraplr.Prefs.boolIsAdmin = jsonObj.boolIsAdmin;
       Scraplr.UI.initPreferencesPane();
       Scraplr.UI.initAdsSection();
     });
   }
};   

Scraplr.Utilities = { 
  arrQSSearchObj: $A([]),
  arrQSSearchTags: $A([]),
  objSearchTextField: $(),
  objSearchSourceList: $$(),
  strLocalSearchCriteria: 'tags',
  intArrQSSearchTagsLength: 0,  
  boolIsXHRLoading : false,
  arrUserTag:[],
  objWindow: '', 
  strDateFormat: '%Y-%m-%d', // get this from user preferences JSON later or from localization, localization is better tho.. :P 
  dateDate : new Date(),
  dateDay : new Date().getDate(),
  dateMonth : new Date().getMonth() + 1,
  dateYear : new Date().getFullYear(),
  timeHours : new Date().getHours(),
  timeMinutes : new Date().getMinutes(),
  intTopScrollOffsets:0,
  openWindow: function (url, intWidth, intHeight) 
  {
   var width  = intWidth;
   var height = intHeight;
   var left   = (screen.width  - width)/2;
   var top    = (screen.height - height)/2;
   var params = 'width='+width+', height='+height;
   params += ', top='+top+', left='+left;
   params += ', directories=no';
   params += ', location=no';
   params += ', menubar=no';
   params += ', resizable=no';
   params += ', scrollbars=no';
   params += ', status=no';
   params += ', toolbar=no';
   Scraplr.Utilities.objWindow = window.open(url,'scraplr', params);
   if (window.focus) {Scraplr.Utilities.objWindow.focus();}
  },
  initWindowObservers: function (){
    Event.observe(window,'scroll', function(event){ 
      Scraplr.UI.hideAutoCompleteResultWrapper();      
    });
    
    Event.observe(window,'resize', function(event){
      Scraplr.UI.initWorkspace();
    });         
    
    Event.observe(window, 'close',function(event){	
      alert('closing window');
      // end observe click
    });    
  },
  initHotKeys: function (){
    Scraplr.Utilities.setHotKey('alt+shift+A', function(){
      Scraplr.UI.openNewEntryDialog();
    });
    Scraplr.Utilities.setHotKey('alt+shift+P', function(){
      console.log("shold be shortcut for add new project");
    });
    Scraplr.Utilities.setHotKey('alt+shift+1',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('tasksBin'));
  	});
  	Scraplr.Utilities.setHotKey('alt+shift+2',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('nextBin'));
  	});
  	Scraplr.Utilities.setHotKey('alt+shift+3',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('scheduledBin'));
  	});
  	Scraplr.Utilities.setHotKey('alt+shift+4',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('projectBin'));
  	});
  	Scraplr.Utilities.setHotKey('alt+shift+5',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('laterBin'));
  	});  	  	                                              
  	Scraplr.Utilities.setHotKey('alt+shift+6',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('completedBin'));
  	});
  	Scraplr.Utilities.setHotKey('alt+shift+7',function(){
      Scraplr.TaskBins.switchActiveTaskBinTab($('recycleBin'));
  	});
  },
  setHotKey: function (strComboKeys, callback, element){
    if (element===undefined){
      new HotKey(strComboKeys,function(event){
        callback();
  	  });
  	} else if (element !== undefined) {
  	  new HotKey(strComboKeys,function(event){
        callback();
  	  },element);
  	} 
  },
  disableRightClick : function (){
    document.observe('mousedown',
    function(e) {
        e.element().oncontextmenu = function() {
           return false;
        };
    });    
  },
  handleFixedElementForWebkit: function (){
    Event.observe(window,'scroll', function(event){
      try{      
        Element.absolutize($('taskCommandContainer'));
        $('taskCommandContainer').setStyle({ top: 145 + document.viewport.getScrollOffsets().top + 'px' });
        Element.absolutize($('header'));
        $('header').setStyle({ top: 0 + document.viewport.getScrollOffsets().top + 'px' });
        Element.absolutize($('newEntrySection'));                                          
        $('newEntrySection').setStyle({ top: $('topBar').offsetHeight + document.viewport.getScrollOffsets().top + 'px' });
      }catch(ex){
        
      }
    });    
  },
  isValidEmail: function(str)
  {
      var s = str.strip();
      var at = "@";
      var dot = ".";
      var lat = s.indexOf(at);
      var lstr = s.length;
      var ldot = s.indexOf(dot);
      if (s.indexOf(at) == -1 || (s.indexOf(at) == -1 || s.indexOf(at) == 0 || s.indexOf(at) == lstr) || (s.indexOf(dot) == -1 || s.indexOf(dot) == 0 || s.indexOf(dot) == lstr) || (s.indexOf(at, (lat + 1)) != -1) || (s.substring(lat - 1, lat) == dot || s.substring(lat + 1, lat + 2) == dot) || (s.indexOf(dot, (lat + 2)) == -1) || (s.indexOf(" ") != -1))
      {
          return false;
      }
      return true;
  },
  checkUserEnteredTagString: function (strTag){
    $$('li.pui-autocomplete-box').each(function(obj){
      var arrTagStrings =  obj.down('span').innerHTML.split('<'); 
      //Scraplr.Utilities.arrUserTag.push()
      try{
          console.log(arrTagStrings[0]);
      }catch(ex){
        
      }        
    });
  },
  selectTaskTag: function  (objTaskTag){
    $$('li.pui-autocomplete-box').each(function(obj){
      obj.removeClassName('pui-autocomplete-selected');           
    });
    objTaskTag.addClassName('pui-autocomplete-selected');
  },
  hasWhiteSpace: function (s){
   reWhiteSpace = new RegExp(/^\s+$/);
   if (reWhiteSpace.test(s)) {
     return false;
   }
   return true; 
  },
  randomize: function() {
    return Math.round(Math.random() * 1000000);
  },
  redirect: function (strResource){
    window.location.href = strResource;
  },
  isIE: function (){
      var objHtmlTag = document.getElementsByTagName("html")[0];
      if(objHtmlTag.hasClassName('ie')){ 
        return true;
      }else{
        return false;
      }
  },
  isEmptyObject: function  (obj) {
      for(var prop in obj) {
          if(obj.hasOwnProperty(prop))
              return false;
      }
      return true;
  },
  readUserId: function() {
    var strUserId = $(document.body).identify().gsub('scraplr_', '');
    return strUserId;
  },
  getUserId : (function(){
    var strUserId;
    return function(){
      strUserId = strUserId || Scraplr.Utilities.readUserId();
      return strUserId;
    };
  })(),
  readUserName: function() {
    var strUserName = $(document.body).classNames().inspect().gsub('#<Enumerable:[\'','').gsub('\']>','').gsub('"','');    
    return strUserName;
  },
  getUserName : (function(){
    var strUserName;
    return function(){
      strUserName = strUserName || Scraplr.Utilities.readUserName();
      return strUserName;
    };
  })(),
  getTaskIds: function (strObjId){
    var arrTaskIds = strObjId.split("_");
    return arrTaskIds; 
  },
  readTaskName : function (strObjId){
    var strTaskName = $('taskItemTitle'+strObjId).innerHTML;
    return strTaskName;
  },
  getSelectedTaskName: function (){
    var arrTaskCaption = [];
    arrTaskCaption.clear(); 
    var strTaskCaptions = '', strTaskCaption='';
    Scraplr.UI.arrSelectedTask.each(function(obj){ 
      strTaskCaption = obj.down('div.taskItemTitle').innerHTML;              
      arrTaskCaption.push(strTaskCaption);           
    });         
    strTaskCaptions = arrTaskCaption.join(', ');     
    return  strTaskCaptions;
  },
  getTaskName: function (strObjId){
     var obj = $(strObjId);
     var strTaskCaption = obj.down('div.taskItemTitle').innerHTML;              
    return  strTaskCaption;
  },  
	startLoadingSpinner: function() {
		this.interval = setInterval(this.animateLoadingSpinner.bind(this), 500);
	},
	stopLoadingSpinner: function() {
		clearInterval(this.interval);
	},
	animateLoadingSpinner: function() {
    console.log('spin loading image');
  },
  objCaramelizedJson : {},
  strCaramelizedHtml : '',
  caramelizeScrap: function (strUrl, boolIsTaskAction, boolReturnJson, objForm, onCreateCallback, onCompleteCallback){
    Scraplr.Utilities.objCaramelizedJson = {}; //reuse object                                                                         
    Scraplr.Utilities.objCaramelizedHtml = ''; //recycle string
    var objAjaxRequest = new Ajax.Request();        
    if(objForm === null){
      objAjaxRequest.options.method = 'get';
    } else {
      try{
        objAjaxRequest.options.parameters = $(objForm).serialize(true);
      } catch(ex){
        log: Prototype.emptyFunction;
      }
    }        
    objAjaxRequest.options.onCreate = function (){
      onCreateCallback();
    };
    objAjaxRequest.options.onComplete = function (response){  
      var strResponse = response.responseText;
      var strResponseValue = strResponse.split(';');
      if(boolIsTaskAction){         
        if(strResponseValue[0] == 'caramelized'){ 
          onCompleteCallback();
        }
      } else if(!boolIsTaskAction){
        if(!boolReturnJson){
            Scraplr.Utilities.objCaramelizedHtml = strResponse;
            onCompleteCallback();          
        }else if(boolReturnJson){ 
            //var jsonObj = eval("(" + strResponse + ")");
            var jsonObj = strResponseValue[0].evalJSON(true);
            Scraplr.Utilities.objCaramelizedJson = jsonObj; 
            onCompleteCallback();          
        }else if(objForm !== null){
            onCompleteCallback();
        }else if((objForm !== null)&&(boolReturnJson)){
          //var jsonObj = eval("(" + strResponse + ")");
          var jsonObj = strResponseValue[0].evalJSON(true);
          Scraplr.Utilities.objCaramelizedJson = jsonObj; 
          onCompleteCallback();
        }
      }
    };
    objAjaxRequest.options.onFailure = function (){
      Scraplr.UI.showDialog ('alert', 'Unable to retrieve data from Scraplr\'s server.<br/>', 'Are you able to browse other sites? <br/>If yes, Scraplr service is likely unavailable.',function (){
      }, function (){
      },false);
    };        
    objAjaxRequest.request(strUrl);
  },
  initQuicksilverSearch: function(field, list) {
    Scraplr.Utilities.objSearchTextField = $(field);
    Scraplr.Utilities.objSearchSourceList = $$(list);
    if (Scraplr.Utilities.objSearchTextField && Scraplr.Utilities.objSearchSourceList) {
      this.setupSearchCache();
      var objForm = Scraplr.Utilities.objSearchTextField.up('form');
      objForm.observe('submit',
      function(e) {
        e.stop();
      });
      Scraplr.Utilities.objSearchTextField.observe('keyup', this.filterSearchResult.bindAsEventListener(this));
      this.filterSearchResult();
    }
  },
  setupSearchCache: function() {
    Scraplr.Utilities.arrQSSearchObj.clear();
    Scraplr.Utilities.arrQSSearchTags.clear();
    Scraplr.Utilities.objSearchSourceList.each(function(obj) { 
      var strCriteria = Scraplr.Utilities.strLocalSearchCriteria;
      switch (strCriteria){
        case 'tags':
          Scraplr.Utilities.arrQSSearchTags.push(obj.down('div.taskItemTags').innerHTML.toLowerCase());
        break;
        case 'title':
          Scraplr.Utilities.arrQSSearchTags.push(obj.down('div.taskItemTags').innerHTML.toLowerCase()+';'+obj.down('div.taskTitleLabel').innerHTML.toLowerCase());
        break;
        case 'note':
        break;
        case 'due':
          Scraplr.Utilities.arrQSSearchTags.push(obj.down('div.taskItemTags').innerHTML.toLowerCase()+';'+obj.down('input.hiddenDue').value.toLowerCase()+';'+obj.down('span.taskDueInWords').innerHTML.toLowerCase());
        break;
        case 'mate':
        break;
      }
      Scraplr.Utilities.arrQSSearchObj.push(obj);
    });                                           
    Scraplr.Utilities.intArrQSSearchTagsLength = Scraplr.Utilities.arrQSSearchTags.length;
  },
  filterSearchResult: function() {
    if (!Scraplr.Utilities.objSearchTextField.present()) {
      Scraplr.Utilities.arrQSSearchObj.invoke('show');
      return;
    }
    this.displayQSSearchResults(this.getSearchScores($F(Scraplr.Utilities.objSearchTextField).toLowerCase()), false);
  },
  displayQSSearchResults: function(scores, boolMultiple) {
    if(!boolMultiple){
      Scraplr.Utilities.arrQSSearchObj.invoke('hide');
    }
    scores.each(function(score) {
      Scraplr.Utilities.arrQSSearchObj[score[1]].show();
    });
  },
  getSearchScores: function(term) {
    var scores = $A([]);
    for (var i = 0; i < Scraplr.Utilities.intArrQSSearchTagsLength; i++) {
      var score = Scraplr.Utilities.arrQSSearchTags[i].score(term);
      if (score > 0) {
        scores.push([score, i]);
      }
    }
    return scores.sort(function(a, b) {
      return b[0] - a[0];
    });
  },
  getTwitterInfo: function(){
    if(false == Scraplr.Utilities.objWindow.closed){
      Scraplr.Utilities.objWindow.close();
      console.log('twitconnect window still open..');
    }else{
      console.log('twitconnect window closed..');
    	var strUrl = '/twitter_info';
      Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
        //Element.show('activityIndicator');
      },function(){
        $('twitter').update(Scraplr.Utilities.objCaramelizedHtml);
        $('disconnectTwitterBt').observe('click',function(event){ 
          var strPreferencesUserTwitName = $('preferencesUserTwitName').innerHTML;
          Scraplr.UI.showDialog ('confirm', 'Are you sure want to disconnect Twitter account "'+strPreferencesUserTwitName+'" from Scraplr?','',function (){
          }, function (){  
             console.log('do function to disconnect');
          },false);	
        // end observe click
        });        
      });   
    }     
  },
  InitTaskCommentPoller: function (){
    var objScraplrTimer = new scraplrTimer(function (objScraplrTimer) {
      Scraplr.Utilities.fetchTaskComment();              
    }, 60000);
  },
  fetchTaskComment: function (){ 
    var strActiveTaskBinId = Scraplr.TaskBins.strActiveTaskBinId;
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/fetch_comment/'+strActiveTaskBinId;
    Scraplr.Utilities.caramelizeScrap(strUrl, false, true, null, function (){
    }, function (){
      var jsonObj = Scraplr.Utilities.objCaramelizedJson;
      var arrTaskWithNewComments = jsonObj.arrTaskWithNewComments;
      for (i=0; i<arrTaskWithNewComments.length; i++) {  
        var strTaskWithNewCommentId = arrTaskWithNewComments[i].strTaskWithNewCommentId.gsub('taskItem','taskItemNewCommentIndy');
        var arrCommentSource = arrTaskWithNewComments[i].strCommentReferrer; 
        var objTaskWithNewComment = $(arrTaskWithNewComments[i].strTaskWithNewCommentId);
        if(objTaskWithNewComment.hasClassName('unfolded')){          
          Scraplr.Utilities.getTaskComment(objTaskWithNewComment.identify());
        }else{
          $(strTaskWithNewCommentId).update(arrCommentSource);
        }      
      }              
    });
    
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/grab_comment/'+strActiveTaskBinId;
    Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){}, function (){});
  },
  getTaskComment: function (strTaskItemId){ 
    var strTaskId = Scraplr.Utilities.getTaskIds(strTaskItemId)[3];
    var strUrl = '/'+Scraplr.Utilities.getUserName()+'/request/get_task_comment/'+strTaskId;
    Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){      
    }, function (){
        var strFormId = strTaskItemId.gsub('taskItem_','postCommentBack_');                
        var strParentIdData = strTaskItemId.gsub('taskItem_','');
        var newComment = Scraplr.Utilities.objCaramelizedHtml; 
        var arrThisCommentList = $('taskCommentList_'+strParentIdData).childElements();
        if(arrThisCommentList.length > 1){
          var strLastCommentId = arrThisCommentList.last().identify();
          $(strLastCommentId).insert({
             after: newComment
          });
          Scraplr.TaskComment.scrollToLatestComment($('taskComment_'+strIds),$(strLastCommentId));
        }else{
          $('taskCommentList_'+strParentIdData).insert(newComment);
        }
        Scraplr.TaskComment.countTaskComments(strParentIdData);                  
    });    
  },
  time_formats : [
      [120, '1 minute ago', '1 minute from now'],
      [3600, 'minutes', 60],
      [7200, '1 hour ago', '1 hour from now'],
      [86400, 'hours', 3600],
      [172800, 'yesterday', 'tomorrow'],
      [604800, 'days', 86400],
      [1209600, 'last week', 'next week'],
      [2419200, 'weeks', 604800],
      [4838400, 'last month', 'next month'],
      [29030400, 'months', 2419200],
      [58060800, 'last year', 'next year'],
      [2903040000, 'years', 29030400],
      [5806080000, 'last century', 'next century']
  ],
  initAdsPoller: function (){  
    var objScraplrTimer = new scraplrTimer(function (objScraplrTimer) {
      var strAdsFusionContent = '<scr' + 'ipt type="text/javascript" src="http://adn.fusionads.net/www/pull/get.php?zoneid=65&charset=UTF-8&withtext=1&cb=' + Math.floor(Math.random() * 99999999999) + '"></scr' + 'ipt>';
      $('fusionAdsContent').update(eval(strAdsFusionContent));              
    }, 60000);
    
  },
  humanizeDate: function (date_str){
      var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," ");
      var dt = new Date;
      var seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000);
      var token = 'ago', list_choice = 1;

      if (seconds < 0) {
          seconds = Math.abs(seconds);
          token = 'from now';
          list_choice = 2;
      }
      if (seconds < 60){
          return 'just now';
      }
      var i = 0, format;
      while (format = Scraplr.Utilities.time_formats[i++]) if (seconds < format[0]) {
          if (i == 0)
              return format[1];
          if (typeof format[2] == 'string')
              return format[list_choice];
          else
              return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;
      }
      // overflow for centuries
      if (seconds > 5806080000)
          return Math.floor(seconds / 2903040000) + ' centuries ' + token;
      return date_str;
  },
  getHumanizedDate: function (strSourceDate){
    var arrDatetime = strSourceDate.split(' ');
    var arrDate= arrDatetime[0].split('-');
    var arrTime= arrDatetime[1].split(':');
    
    var intDay = parseInt(arrDate[2],10);
    var intMonth = parseInt(arrDate[1],10)-1;
    var intYear = parseInt(arrDate[0],10);      
    
    var intHour = parseInt(arrTime[0],10);
    var intMinute = parseInt(arrTime[1],10);
    
    var dateConfig = {minute:intMinute, hour:intHour, day:intDay, month:intMonth, year:intYear}; 
    var dateNewDate = Date.today().set(dateConfig);  
    
    var strNewISODate = dateNewDate.toISOString().gsub('"','').gsub('.000Z','Z');     
    strNewHumanizedDate = Scraplr.Utilities.humanizeDate(strNewISODate);
    
    return strNewHumanizedDate;
  },
  triggerDialogCallback: function(intFunctionIndex) {
      if ('function' == typeof Scraplr.UI.arrDialogCallbacks[intFunctionIndex]) {
          Scraplr.UI.arrDialogCallbacks[intFunctionIndex].call(this);
      }
  },
  isControlKeyPressed: function(e) {
    if ((e.ctrlKey)||(e.metaKey)) {
      boolIsControlKeyPressed = true;
    } else {
      boolIsControlKeyPressed = false;
    }
    return boolIsControlKeyPressed;
  }      
};
 
Scraplr.FbConnect = {
  isConnectedToFacebook: false,
  InitFbConnect: function (){
    FB.Bootstrap.requireFeatures(["Connect"], function() {
      FB.Connect.get_status().waitUntilReady(function(status) { 
        switch (status) { 
          case FB.ConnectState.connected:             
            Scraplr.FbConnect.isConnectedToFacebook = false;
            console.log('loggedIn',Scraplr.FbConnect.isConnectedToFacebook);
          break; 
          case FB.ConnectState.appNotAuthorized: 
            //FB.Connect.requireSession(); 
            Scraplr.FbConnect.isConnectedToFacebook = true;  
              //$('fbConnectWrapper').innerHTML = '<a href="#" onclick="Scraplr.FbConnect.ShowAppPermissionDialog();"> <img id="fb_login_image" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_dark_medium_long.gif" alt="Connect" /> </a>';
            console.log('case FB.ConnectState.appNotAuthorized, appNotAuthorized, Scraplr.FbConnect.isConnectedToFacebook',Scraplr.FbConnect.isConnectedToFacebook);
          break;
          case FB.ConnectState.userNotLoggedIn: 
            //FB.Connect.requireSession();               
            Scraplr.FbConnect.isConnectedToFacebook = false;
            if(!Scraplr.FbConnect.isConnectedToFacebook){
              
            }
            //$('fbConnectWrapper').innerHTML = '<a href="#" onclick="Scraplr.FbConnect.ShowAppPermissionDialog();"> <img id="fb_login_image" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_dark_medium_long.gif" alt="Connect" /> </a>';
            console.log('case FB.ConnectState.userNotLoggedIn, Scraplr.FbConnect.isConnectedToFacebook',Scraplr.FbConnect.isConnectedToFacebook);
          break;
        }
      });
    });
  },
  ShowAppPermissionDialog: function (){
    FB.Bootstrap.requireFeatures(["Connect"], function() {      
        FB.Connect.showPermissionDialog('publish_stream, read_stream, email, offline_access', Scraplr.FbConnect.getUserFacebookProfile, true, null);
      });
  },
  FbLogout: function (){
    FB.Connect.logout(function() { window.location = 'http://alpha.scraplr.com/'; });
  },
  getUserFacebookProfile: function (){
    //var intRandom = Scraplr.Utilities.randomize();
    //var strUrl = 'request/facebook_info/';
	var strUrl = '/facebook_connect';
    Scraplr.Utilities.caramelizeScrap(strUrl, false, false, null, function (){
      //Element.show('activityIndicator');
    },function(){
      var StrHtml = Scraplr.Utilities.objCaramelizedHtml;
      if(StrHtml!=''){
       $('userConnectedToFBNote').update(Scraplr.Utilities.objCaramelizedHtml); 
       $('userNotConnectedToFBNote').hide();
       $('userConnectedToFBNote').show();
       $('disconnectFacebookBt').observe('click',function(event){ 
         var strPreferencesUserFBName = $('preferencesUserFBName').innerHTML;
         Scraplr.UI.showDialog ('confirm', 'Are you sure want to disconnect Facebook account "'+strPreferencesUserFBName+'" from Scraplr?','',function (){
         }, function (){  
            console.log('do function to disconnect');
         },false);         
       // end observe click
       });
      }                  
    });
  },
  initFbConnectStatusMessage: function  (){
    Scraplr.FbConnect.getUserFacebookProfile();
    if(Scraplr.FbConnect.isConnectedToFacebook){
      $('userNotConnectedToFBNote').hide();
      $('userConnectedToFBNote').show();
      Scraplr.FbConnect.getUserFacebookProfile();
    }else{
      $('userNotConnectedToFBNote').show();
      $('userConnectedToFBNote').hide();
    }
  }
};


Object.extend(Array.prototype, {
  pull : function(strArrayElement) {
    var i = this.indexOf(strArrayElement);
    if (i != -1) {
      this.splice(i, 1);
    }
  },
  locate : function(searchStr) {
    var returnArray = false;
    for (i=0; i<this.length; i++) {
      if (typeof(searchStr) == 'function') {
        if (searchStr.test(this[i])) {
          if (!returnArray) {returnArray = [];}
          returnArray.push(i);
        }
      } else {
        if (this[i]===searchStr) {
          if (!returnArray) {returnArray = [];}
          returnArray.push(i);
        }
      }
    }
    return returnArray;
  },
  locateSubString : function(searchStr) {
    var returnArray = false;
    var strRegExPattern = '^'+searchStr;
    for (i=0; i<this.length; i++) {
      if (typeof(searchStr) == 'function') {
        if (searchStr.test(this[i])) {
          if (!returnArray) {returnArray = [];}
          returnArray.push(i);
        }
      } else {
        if (this[i].match(new RegExp(strRegExPattern,'g'))) {
          if (!returnArray) {returnArray = [];}
          returnArray.push(i);
        }
      }
    }
    return returnArray;
  }  
});

//killer quicksilver search below -->
Object.extend(String.prototype,{
  score: function(abbreviation,offset) {
    offset = offset || 0 ;

    if(abbreviation.length == 0) return 0.9;
    if(abbreviation.length > this.length) return 0.0;

    for (var i = abbreviation.length; i > 0; i--) {
      var sub_abbreviation = abbreviation.substring(0,i);
      var index = this.indexOf(sub_abbreviation);


      if(index < 0) continue;
      if(index + abbreviation.length > this.length + offset) continue;

      var next_string       = this.substring(index+sub_abbreviation.length);
      var next_abbreviation = null;

      if(i >= abbreviation.length)
        next_abbreviation = '';
      else
        next_abbreviation = abbreviation.substring(i);

      var remaining_score   = next_string.score(next_abbreviation,offset+index);

      if (remaining_score > 0) {
        var score = this.length-next_string.length;

        if(index != 0) {
          var j = 0;

          var c = this.charCodeAt(index-1);
          if(c==32 || c == 9) {
            for(var j=(index-2); j >= 0; j--) {
              c = this.charCodeAt(j);
              score -= ((c == 32 || c == 9) ? 1 : 0.15);
            }
          } else {
            score -= index;
          }
        }

        score += remaining_score * next_string.length;
        score /= this.length;
        return score;
      }
    }
    return 0.0;
  }
});

var scraplrTimer = Class.create({
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;
    this.registerCallback();
  },
  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency);
  },
  execute: function() {
    this.callback(this);
  },
  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },
  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});

Scraplr.InlineLabel = Class.create({
	initialize : function(){
	  // Select all textboxes and assign them to an array
	  var textboxes = $$('form.mobileme input.input-text');
	  // Iterate through all textboxes in the form
	  textboxes.each(function(input, index){
	    var label = input.previous();
	    // TimedObserver to check for autocomplete	
	    if (index == 0){
	      new Form.Observer(input.up('form'), 0.1, function(form, value) {
	        textboxes.each(function(inputX){
	          if (!inputX.value.empty()) {
	            inputX.previous().addClassName('hastext');
	          }
	        });
	      });
	    }
	    // Fade the label back when a field gains focus		
	    input.onfocus = function(){
	      if (input.value.empty()){
	        label.addClassName('focus');            
	      }
	    };
	    // Check if a field is empty when the user switches out
	    input.onblur = function(){
	      if (input.value.empty()){
	        label.removeClassName('focus').removeClassName('hastext');          
	      }
	    };
	    // Fade the label back if a field has text		
	    if (!input.value.empty()) {
	      label.addClassName('hastext');
	    }else{
		label.removeClassName('hastext');
		}
		
		
	    // Fade the label back when the user starts to type		
	    input.onkeypress = function(){
	      label.addClassName('hastext');
	    };
	  });
	}
});

/*
statement example :
new scraplrTimer(function (objScraplrTimer) {
console.log('spinner loading');              
	if (!Scraplr.Utilities.boolIsXHRLoading){
    objScraplrTimer.stop();
  }
}, 1000);
*/