//  @import com.hedgehoglab.application.view.BaseView;
//	@import com.hedgehoglab.solomon.view.TaskListView;
	
function ContactNTView(scope){

  BaseView.call(this,scope);
  var _this = this;
  var _helpers=new _this.generate_helpers(this,[ContactViewHelper,TagHelper]);
  var _users = null;
  

  this.setElement=function(element){
      scope.element=element;
  };
  
  this.get_users=function()
  {
    return _users;
  };
  
  this.render = function(model){
	// alert("RENDERING")
    var t=scope.element;
    var flag=false;
    var s=null;

    var _view={};
    var _view2={};

    ContactViewHelper.call(_view,scope);

    $.extend(_view,_this);
      
    _users = model.users;
    _model=$.extend(model,scope.general_types_model.get_types());
    _this.render_template_with_view('contacts/ContactNoteTask',_model,_helpers,function(f){
		
        
      $(scope.element).html(f);
      new TabPane({
         element:$(scope.element),
         tabs:'div.Tabs ul li',
         pane:'div.contact-tab-panel',
         current:'current',
         hide:'hide'
      });
      
      var ff=$(scope.element);

	var contact_tasks_list=$('#contact-tasks-list',ff);

	var _groups=null;
	
	function render_task_ui(){
		if(model.tasks){
			sort_tasks();
		}
		_groups=_helpers.group_tasks(model.tasks);	
		render_groups();
	}
	
	function sort_tasks(tasks){
        model.tasks.task=model.tasks.task.sort(function(a,b){
            if(a.dueOn!=null && b.dueOn!=null){
                //  Todo, precalculate dates in another array, this is slow

                var _a=Date.parse(a.dueOn);
                var _b=Date.parse(b.dueOn);
                return _b.compareTo(_a);
            }else{
                //alert("No Date in a or b");
            }
        });

        return model.tasks.task;
    }
	
	
	
	function render_groups(){
		$.each(_groups,function(index,group){
			var dl=$("."+group.css,contact_tasks_list)[0];
			var dl_node=(dl==null)?null:$(dl);
			
			if(null==dl_node){
				_this.render_template_with_view('task_list_group',{
		            group:group
		        },_helpers,function(f){
					dl_node=$(f);
				});
				contact_tasks_list.append(dl_node);
			}
			if(group.tasks.length>0){
				$.each(group.tasks,function(i,n){
						var dd=$("dd.task[rel='"+n.id+"']",contact_tasks_list)[0];
						var node=(dd==null)?null:$(dd);
						if(node==null){
							_this.render_template_with_view('contact_task',{
					            task:n,
					            taskTypes:scope.general_types_model.get_types().taskTypes
					        },_helpers,function(f){
								node=$(f);
							});

							$('input.task-checkbox',node).bind('click',function(e){
								_this.raise_event('on_task_complete_change',{task:{id:$(node).attr('rel')},
								paint:function(e){
								render_task_ui();								
								}});
							});
						}
						
						$(node).removeClass('hover');
	                    node.hover(function(e){
	                    	$(this).addClass('hover');
	                    },function(e){
	                        $(this).removeClass('hover');
	                    });
	
						//	Append it to the right group
						node.insertAfter($('dt',dl_node));
					});
				dl_node.show();
			}else{
				dl_node.hide();
			}
			
			
			//	Render the tasks
		});
	}
	
	render_task_ui();
	
	$.each($(".note-list > dd",ff),function(i,n){
		//alert("asdasd")
		add_actions_to_note($(n));
	});


      function add_actions_to_note(dd,note){
	
        dd.hover(function(e){
            $(this).addClass('hover');
        },function(e){
            $(this).removeClass('hover');
        });

		$('li#cancel-action a',dd).bind('click',function(e){
			$(dd).removeClass('editing');
			$('textarea',dd).val("");
			return false;
		});

          $('li#confirm-action a',dd).bind('click',function(e){
              var _working_note=null;
              $.each(model.notes,function(i,n){
					if(n!=null){
                  if(n.id==dd.attr('rel')){
                      _working_note=n;
                  }
}
              });


              _working_note.body = $('textarea',dd).val();
              
              // Delete this note
              _this.raise_event('on_edit_note',{
                  contact:model.contact,
                  note:_working_note,
                  paint:function(){
                      // alert("Saved");
                      $(dd).removeClass('editing');
                      $('#view-box',dd).html(_helpers.parse_note_body(_working_note.body));
                      //    Put the value of the tex box into the dd
                  }
              });
              return false;
          });

		// The action.
		$('li#delete-action a',dd).click(function() {
		  	  // Delete this note
			_this.raise_event('on_delete_note',{
			    contact:model.contact,
			    note_id:dd.attr('rel'),
			    paint:function(){
			        //alert("asdasd");
			        dd.slideUp(function(e){
			           dd.remove(); 
			        });
			    }
			});
			return false;
		});
		
		$('li#delete-action a',dd).confirm({});

		$('li#delete-action a',dd).bind('afterConfirm',function(e){
			dd.removeClass('is_deleting');
			$('li#edit-action a',dd).show();
		});

		$('li#delete-action a',dd).bind('beforeConfirm',function(e){
			$('li#edit-action a',dd).hide();
			dd.addClass('is_deleting');
			//	Set the status of this note to delete so the action is always visible
		});
		


          $('li#edit-action a',dd).bind('click',function(e){
              var _working_note=null;
			$.each(model.notes,function(i,n){
				if(n){
                  if(n.id==dd.attr('rel')){
                      _working_note=n;
                  }
				}
              });		
				

              if(_working_note){
                  $('textarea',dd).val(_working_note.body);
              }
              $(dd).addClass('editing');
            
              return false;

          });
		  $('.note-meta em abbr',dd).timeago();
      };

      //  On add confirm
      $('#add-note-action',ff).bind('click',function(e){
          var body=$('#add-note-body',ff).val();
          //  Add note message

		//	Disable the add button and the note field
		$('#add-note-body',ff).attr('disabled',true);
		
		
		$('#add-note-action',ff).attr('disabled',true);
		//	Show loading wheel in place of button
		$('#add-note-action',ff).hide();
		$('#add-note-action',ff).parent().parent().append('<li class="ajax-loading">Adding Note</li>');
			
          _this.raise_event('on_add_new_note',{contact:model.contact,body:body,paint:function(new_note,notes){
              model.notes=notes;
              var dd=null;
				
              _this.render_template_with_view('contact_note',{note:new_note},_helpers,function(f){
                  dd=$(f);
				  add_actions_to_note($(dd));
                  var img=$('img',dd);
                  img.bind('load',function(e){
                      show_note();
                  });
					
					$('#add-note-action',ff).show()
					$('.ajax-loading',$('#add-note-action',ff).parent().parent()).remove();
              });

              

              dd.hide();


              $('.notes-left-today',ff).removeClass('hide');
              
              var fdd=$('.notes-left-today dd',ff)[0];
              if(fdd){
                  $(dd).insertBefore(fdd);
              }else{
                $('.notes-left-today',ff).append(dd);    
              }
				
              function show_note(){
                  $('.note-meta em abbr',dd).timeago();
                  dd.fadeIn(function(e){
					$('#add-note-body',ff).attr('disabled',false);
					$('#add-note-body',ff).val("");
					$('#add-note-action',ff).attr('disabled',false);
					$('#add-note-body',ff).removeAttr('disabled',false);
					
				});
              };
          }});



      });


        $('#add-task-action',ff).bind('click',function(e){
	
			$('#add-task-action',ff).attr('disabled',true);
			//	Show loading wheel in place of button
			$('#add-task-action',ff).hide();
			$('#add-task-action',ff).parent().parent().append('<li class="ajax-loading">Adding Task</li>');
	
            var _current_user_id=$("meta[name='current_user_id']").attr('content');
            var type=$("select[name='taskType']",ff).val();
            var assignedTo=$("select[name='assignTo']",ff).val();
            // Grab the date string
            var dueOn=$("input[name='due']",ff).val();
            // Turn it into a Date object
            dueOn = Date.parse(dueOn);
            // Set the time as 1 minute to midnight
            dueOn.setHours(23);
            dueOn.setMinutes(59);
            // Turn it back into a String (nice ISO format)
            dueOn = dueOn.toString("yyyy-MM-ddTHH:mm:ssZ");

            var title=$("#contact-tasks #add-task-form input[name='description']",ff).val();

            _this.raise_event('on_add_new_task',{
                contact:model.contact,
                task:{
                    type:parseInt(type),
                    assignedTo:parseInt(assignedTo),
                    dueOn:dueOn,
                    title:title,
                    complete:false,
                    contact:parseInt(model.contact.id)
                },
                paint:function(new_task){
	// alert("Asdasd");
					$("#contact-tasks #add-task-form input[name='description']",ff).val("");
					$('#add-task-action',ff).attr('disabled',false);
					$('#add-task-action',ff).show()
					$('.ajax-loading',$('#add-task-action',ff).parent().parent()).remove();
					render_task_ui();
                }
            });
            return false;
        });

      //Set relative dates
      $('.timeago').timeago();

      $("input[name='due']",ff).val((Date.today().toString('dd MMM yyyy')));
      
      $("input[name='due']",ff).datepicker({
        clickInput:true,
        constrainInput:true,
        dateFormat:'dd M yy',
        minDate:Date.today(),
        showButtonPanel:true,
        numberOfMonths:1});

            //  On add confirm

      
    });
  };
};