//  @import com.hedgehoglab.application.view.BaseView;
//	@import com.hedgehoglab.application.helper.BaseHelper;
//  @import com.hedgehoglab.solomon.helper.ContactViewHelper;

function TaskListView(scope){
    BaseView.call(this,scope);
	ContactViewHelper.call(this,scope);
	
    var _this=this;
    var _task_items={};
    var _complete_tasks=$('.complete-tasks',scope.element);
    var _active_tasks=$('.active-tasks',scope.element);
	var _is_editing=false;

    this.render=function(model){
		_is_editing=false;
		scope.element.removeClass('is_editing');

        //  If there are tasks
        if(model.tasks){

            var assignee_options="";$.each(model.users.user,function(i,n){
				if(n.enabled=='true'){
					assignee_options+='<option value="'+n.id+'">'+_this.user_fullname(n)+ '</option>';
				}
			});
            var type_options="";$.each(model.task_types.taskType,function(i,n){type_options+='<option value="'+n.id+'">'+n.name+ '</option>'});
            var contact_options="<option value='-1'>No contact associated</option>";$.each(model.contacts.contact,function(i,n){contact_options+='<option value="'+n.id+'">'+n.firstName+' ' + n.lastName+ '</option>'});
			var deals_options="<option value='-1'>No deal associated</option>";$.each(model.deals.deals,function(i,n){deals_options+='<option value="'+n.id+'">'+n.name+ '</option>'});
			var _last_complete=$("dt",_complete_tasks);
            var _last_active=$("dt",_active_tasks);


            //  Build lookup for tasks by id
            var _types_lookup={};
            $.each(model.task_types.taskType,function(i,n){
				_types_lookup[""+n.id]=n;
                _types_lookup[""+n.id].index=i;
            });

            //  Build lookup for users by id
            var _users_lookup={};
            $.each(model.users.user,function(i,n){
                _users_lookup[""+n.id]=n;
                _users_lookup[""+n.id].index=i;
            });

            //  Mark the class as old
            $('.task-list dd.task',scope.element).addClass('marked');

            //  Remove the hover and edit state
            $('.task-list dd.task',scope.element).removeClass('hover');
			
            //$('.task-list dd.task',scope.element).removeClass('editing');

            //  Values to count the number of complete/incomplete
            var _complete=0;
            var _active=0;
			var _fade_count=0;
			
			
			function update_edit(node,n){
                $('.due-date',node).attr("title",""+n.dueOn);
				$('.due-date',node).timeago();
				$(".date_field",node).val(Date.parse(n.dueOn).toString("dd MMM yyyy"));
				
				//  Add an overdue class if its after today
                if(Date.parse(n.dueOn).compareTo(Date.today())==-1){
                    node.addClass('overdue-task');
                }else{
				    node.removeClass('overdue-task');
				}
			}
            $.each(model.tasks.all,function(i,n){

                //  Check to see if the node already exists before we go adding another dom element
                var dd=$("dd[rel='"+n.id+"']",scope.element)[0];
                var node=(dd!=null)?$(dd):null;
				var n_clone=$.extend({},n);
				
                //  If it is null create another
                if(node==null){
					
                    node=$('#task-temlate > dd.task').clone().attr('id','');
                    node.attr('rel',n.id);
                    
					update_edit(node,n);

					$(".date_field",node).bind('keydown',function(){return false;});
					
					$(".date_field",node).datepicker({
						clickInput:true,
						constrainInput:true,
						dateFormat:'dd M yy',
						// minDate:Date.parse(n.dueOn),//Date.today(),
						showButtonPanel:true,
						numberOfMonths:1
					});
                  
                    $('p',node).html(n.title);

                    $('select.contact_field',node).html(contact_options);
					// $('select.contact_field',node).val(""+node);
					
					$('select.deal_field',node).html(deals_options);
					// $('select.deal_field',node).val(""+node);

					//	Tis borked here 
					// console.log(_contacts_lookup);
					// console.log(model.contacts_lookup);
					
					if(n.contact){
						$('select.contact_field',node).val(""+n.contact);
						$('span.relates-to-contact',node).show();
						$('strong.contact a',node).html(""+model.contacts_lookup[""+n.contact].firstName+' '+model.contacts_lookup[n.contact].lastName).attr('href','/contacts#'+model.contacts_lookup[n.contact].id);
					}else{
						$('span.relates-to-contact',node).hide();
						$('strong.contact a',node).html("");
						$('select.contact_field',node).val("-1");
					}
					
					if(n.deal){
						$('select.deal_field',node).val(""+n.deal);
						$('span.relates-to-deal',node).show();
						$('strong.deal a',node).html(""+model.deals_lookup[""+n.deal].name).attr('href','/deals#'+model.deals_lookup[n.deal].id);
					}else{
						$('span.relates-to-deal',node).hide();
						$('strong.deal a',node).html("");
						$('select.deal_field',node).val("-1");
					}
					
					// if(n.contact){
					// 					$('select.contact_field',node).val(""+n.contact);
					//                     $('strong.contact a',node).html(""+model.contacts_lookup[""+n.contact].firstName+' '+model.contacts_lookup[n.contact].lastName).attr('href','/contacts#'+model.contacts_lookup[n.contact].id);
					// 				}

					$('strong.contact a',node).bind('click',function(e){
						window.location.href=$(this).attr('href');
						return false;
					});
					
					// if(n.deal){
					// 						$('select.deal_field',node).val(""+n.deal);
					// 	                    $('strong.deal a',node).html(""+model.deals_lookup[""+n.deal].name).attr('href','/deals#'+model.deals_lookup[""+n.deal].id);
					// 					}
					
					
					
					// deal
					
					
					$('select.assignee_field',node).html(assignee_options);
					$('select.assignee_field',node).val(""+n.assignedTo);
                    
                    $('select.type_field',node).html(type_options);
					$('select.type_field',node).val(""+n.type);
                    $('strong.type',node).html(""+_types_lookup[""+n.type].name);


                    

					if(n.complete=="true"){
                        node.addClass('complete-task');
                    }

                    node.show();

                        //  Add the events
                    $("input[type='checkbox']",node).bind('click',function(e){
						//	Add the ajaxloading class
						node.addClass('checking');
                        _this.raise_event('on_task_checked',{
                            task:n,
                            paint:function(e){
                                node.removeClass('editing');
                            }
                        });
						e.stopPropagation();
                    });


                    $("input[type='checkbox']",node).bind('focus',function(e){
                        node.addClass('hover');
                    });

                    $("input[type='checkbox']",node).bind('blur',function(e){
                        node.removeClass('hover');
                    });

                    //  If its complete
                    if(n.complete=="true"){
                        $("input[type='checkbox']",node).attr('checked','checked');
                        _complete++;

                    }else{
                        $("input[type='checkbox']",node).attr('checked','');
                        _active++;
                    }


                    node.hover(function(e){
                        if(_is_editing==false) $(this).addClass('hover');

                    },function(e){
                        if(_is_editing==false) $(this).removeClass('hover');

                    });

					function switch_title(node){
						var tt=node.attr('title');
						var rr=node.attr('rel');
						node.attr('title',rr);
						node.attr('rel',tt);
					}
					

					node.bind('click',function(e){
						if(_is_editing==false){
							$('input.value',node).val($('p',node).html());
	                        node.addClass('editing');
							_is_editing=true;
							scope.element.addClass('is_editing');
						}
						return false;
					});
					
					$('a.cancel-action',node).bind('click',function(e){
						node.removeClass('editing');
						_is_editing=false;
						scope.element.removeClass('is_editing');
						return false;
					});
					
                    //$('a.save-action',node).bind('click',function(e){
					$('a.save-action',node).bind('click',function(e){
							_is_editing=false;
							
							
							node.removeClass('editing');
							
							n.type = $('.type_field',node).val();
	                        n.assignedTo = $('.assignee_field',node).val();
							n.contact = $('.contact_field',node).val();
							if(n.contact=="-1") n.contact=null;
							
							n.deal = $('.deal_field',node).val();
							if(n.deal=="-1") n.deal=null;
							
							n.title = $('input.value',node).val();
							var ddate=$(".date_field",node).datepicker('getDate');
							
							//	Add a day and remove a minute
							ddate.addDays(1).addMinutes(-1);
							
							n.dueOn=ddate.toString("yyyy-MM-ddTHH:mm:ssZ");
							update_edit(node,n);
							
                            node.addClass('ajaxLoading');
                             _this.raise_event('on_task_updated',{
                                task:n,
                                paint:function(e){
									if(e==true){
										node.removeClass('ajaxLoading');scope.element.removeClass('is_editing');

										$('strong.type',node).html(""+_types_lookup[""+n.type].name);
										$('p',node).html($('input.value',node).val());
										if(n.contact){
											$('span.relates-to-contact',node).show();
											$('strong.contact a',node).html(""+model.contacts_lookup[""+n.contact].firstName+' '+model.contacts_lookup[n.contact].lastName).attr('href','/contacts#'+model.contacts_lookup[n.contact].id);
										}else{
											$('span.relates-to-contact',node).hide();
											$('strong.contact a',node).html("");
											$('select.contact_field',node).val("-1");
										}
										
										if(n.deal){
											$('span.relates-to-deal',node).show();
											$('strong.deal a',node).html(""+model.deals_lookup[""+n.deal].name).attr('href','/deals#'+model.deals_lookup[n.deal].id);
										}else{
											$('span.relates-to-deal',node).hide();
											$('strong.deal a',node).html("");
											$('select.deal_field',node).val("-1");
										}
									}else{
										//alert("FAIL!")
										// node.remove();
									}
                                    
                                    //	@TODO	-	Set the due date
                                }
                            });

							//	Compare n to clone
							//	If anything has changed, add the changed class!
							node.addClass('is-dirty');
                           
						return false;
                    });

                    //  Bind to edit fields
                    $('.type_field',node).bind('change',function(e){
                        //
                    });
					$('.type_field',node).bind('click',function(e){return false});

                    $('.assignee_field',node).bind('change',function(e){

                    });
					$('.assignee_field',node).bind('click',function(e){return false});
					
                    $('input.value',node).bind('keyup',function(e){
                        
                        
                    });

					$('.date_field',node).bind('click',function(e){return false});
					// $('.assignee_field',node).bind('change',function(e){
					//                         n.assignedTo = $('.assignee_field',node).val();
					//                     });
//					$('.type_field',node).bind('click',function(e){return false});
					
					$('input.value',node).bind('click',function(e){return false});
                   //node.fadeIn();
                }

                //  If its complete
                if(n.complete=="true"){
                    _complete++;
					node.addClass('complete-task');
                }else{
                    _active++;
					node.removeClass('complete-task');
                }

                //  Get the parent node and where it should be from and to (if it is moving)
                var parent=node.parent()[0];
                var par_fr=null;
                var par_to=null;


                //  If its complete
                if(n.complete=="true"){
                    //  Move it to where it would come from
                    par_fr=_last_complete[0];//_complete_tasks[0];
                    par_to=_complete_tasks[0];
                }else{
                    par_fr=_last_active[0];
                    par_to=_active_tasks[0];
                }

                //  If Its in the wrong place
                if(par_to!=parent){
					node.fadeOut(function(e){
						node.removeClass('checking');
                        node.insertAfter(par_fr);
                        node.fadeIn();
                    });

                }else{
                    //  Leave it where it is
                }



                $(node).removeClass('marked');

            });


            $('.task-list dd.marked',scope.element).remove();

			
            

			//show_feedbacks();
        }else{

        }
      //    If it does not exist, create it
      
    };
};
