//	@import com.hedgehoglab.application.helper.BaseHelper;


function ContactViewHelper(scope){
	BaseHelper.call(this,scope);
	var _this=this;
	
  this.get_user=function(id)
  {
    result = {id:-1,firstName:"Unknown",lastName:"User"}
    $.each(scope.get_users().user,function(i,n){
      if (n.id == id) {result = n; return 0;}
    });
    return result;
  };
	this.user_is_admin=function(user){
		if(user.roles){
			return user.roles.role[0].id=="1";
		}else{
			return false;
		}
	};
	
	this.can_user_role_be_changed=function(current_user,user){
		if(!_this.user_is_admin(current_user) || current_user.id==user.id){
			//	Yes the user can have their role changed
			return true;
		}
		
		return false;
	};
	
	this.user_fullname=function(user){
		var username="";
		if((user.firstName==null || user.firstName=="") && (user.lastName==null || user.lastName=="")){
			//	Revert to the username
			username=user.username;
		}else{
			username=user.firstName+" "+user.lastName;
		}
		
		return username;
	};



  this.lookup_task_type=function(types,id)
  {
    var result = {id:-1,label:"Unknown Type"}
    $.each(types,function(index,type){
      if (type.id==id) {result = type; return 0;}
    });
    return result;
  }

   this.get_time_ago=function(date){
        return date//;Date.parse(date).toString("yyyy-MM-ddTHH:mm:ssZ");
    };

    this.parse_note_body=function(body){
        return String(""+body).replace(/\n/gi,"<br/>");
    };

    this.get_addresses=function(addresses){
        if(addresses!=null && addresses[0]!=null){
            if(!$.isArray(addresses[0].address)){
                return [addresses[0].address];
            }else{
                return addresses[0].address;
            }
        }
        return [];
    };

    this.get_phoneNumbers=function(phoneNumbers){
        if(phoneNumbers!=null && phoneNumbers[0]!=null){
            if(!$.isArray(phoneNumbers[0].phoneNumber)){
                return [phoneNumbers[0].phoneNumber];
            }else{
                return phoneNumbers[0].phoneNumber;
            }
        }
        return [];
    };

    this.get_websites=function(websites){
        if(websites!=null && websites[0]!=null){
            if(!$.isArray(websites[0].website)){
                return [websites[0].website];
            }else{
                return websites[0].website;
            }
        }
        return [];
    };

    this.get_tags=function(_contact){
        if(_contact.tags != null){
            return _contact.tags;
        }
        return [];
    };

    this.get_tasks=function(contact){
        
        var sorted_tasks=[];
        //  Sort
        if(contact.task!=null){
            if(contact.task[0]!=null){
                sorted_tasks=contact.task.sort(function(a,b){
                    if(!(b.dueOn==null || a.dueOn==null)){
                      res=Date.compare(Date.parse(b.dueOn),Date.parse(a.dueOn));
                        if(res==0){
                            if(!(b.createdAt==null || a.createdAt==null)){
                                res=Date.compare(Date.parse(b.createdAt),Date.parse(a.createdAt));
                            }else{
                                res=false;

                            }
                        }
                    }
                    return res;
                });
            }
        }


        return sorted_tasks;
    };

    this.get_notes=function(contact){
        var sorted_notes=[];
        
        //  Sort
        if(contact.note!=null){
            if(contact.note[0]!=null){
                sorted_notes=contact.note.sort(function(a,b){
                    res=Date.compare(Date.parse(b.createdAt),Date.parse(a.createdAt));
                    return res;
                });
            }
        }
        return sorted_notes;
    };

    this.determine_task_group=function(task){
        var groups=this.group_tasks({task:[task]});
        var the_group=null;

        $.each(groups,function(i,n){
           if(n.tasks.length!=0){ the_group=n;}
        });

        return the_group;
    };

    this.group_tasks=function(tasks){
        var sorted_tasks=tasks;
        var groups=[
            {
                "title":"Overdue",
                css:"tasks-overdue",
                tasks:[],
                check:function(task){
                    var d=Date.parse(task.dueOn).clearTime();
                    if(task.complete!="true") return (Date.today().compareTo(d)==1);
                    else return false;
                }
            },
            {
                "title":"Today",
                css:"tasks-due-today",
                tasks:[],
                check:function(task){
                    var d=Date.parse(task.dueOn).clearTime();
                    if(task.complete!="true") return (Date.today().compareTo(d)==0);
                    return false;
                }
            },
			{
                "title":"Tomorrow",
                css:"tasks-due-tomorrow",
                tasks:[],
                check:function(task){
                    var d=Date.parse(task.dueOn).clearTime();
                    if(task.complete!="true") return (Date.today().addDays(1).compareTo(d)==0);
                    return false;
                }
            },
            {
                "title":"Future",
                css:"tasks-due-this-year",
                tasks:[],
                check:function(task){
                    //var d=Date.parse(task.dueOn).clearTime();
                    //return (Date.today().moveToFirstDayOfMonth().compareTo(d)==0);
                    if(task.complete!="true") return true;
                    else return false;
                }
            },
            {
                "title":"Complete",
                css:"complete-tasks",
                tasks:[],
                checked:true,
                check:function(task){
                    return true;
                }
            }
        ];

        if(tasks!=null && tasks.task!=null){
            $.each(tasks.task,function(i,n){

                var flag=false;
                $.each(groups,function(ii,nn){
                    if(!nn.lookups) nn.lookups=[];
                    if(flag==false){
                        if(nn.check(n)){
                            nn.tasks.push(n);
                            flag=true;
                            nn.lookups.push(i);
                        }
                    }
                });
            });
        }
        
        
        return groups;
    };

    this.group_notes=function(notes){
        var sorted_notes=notes;
		
		//	Calculates the timezone difference and takes it away from 24 hours
		function localTime(d){
			var theDate = d.clone(); 
			var now=new Date();
            var utcHours=parseInt(now.getUTCHours());
			var hours=parseInt(now.getHours());
			
            if (theDate) {
				theDate.addHours(+(hours-utcHours)); 
            }
			return theDate;
		}
		
        var groups=[
            {
                "title":"Left Today",
                css:"notes-left-today",
                notes:[],
                check:function(note){
                    var d=Date.parse(note.createdAt)
					
					var e=localTime(d).clearTime();
                    return (Date.today().compareTo(e)==0);
                }
            },
            {
                "title":"Left Yesterday",
                css:"notes-left-yesterday",
                notes:[],
                check:function(note){
                    var d=Date.parse(note.createdAt);
					var e=localTime(d).clearTime();
                    return (Date.today().addDays(-1).compareTo(e)==0);
                }
            },
            // {
            //     "title":"Left This Month",
            //     css:"notes-left-this-month",
            //     notes:[],
            //     check:function(note){
            //         var d=Date.parse(note.createdAt).clearTime().moveToFirstDayOfMonth();
            //         return (Date.today().moveToFirstDayOfMonth().compareTo(d)==0);
            //     }
            // },
            {
                "title":"Left Recently",
                css:"notes-left-recently",
                notes:[],
                check:function(note){
                    var d=Date.parse(note.createdAt).clearTime().moveToFirstDayOfMonth();
					// var e=localTime(d);
                    //return (Date.today().moveToFirstDayOfMonth().compareTo(d)==0);
                    return true;
                }
            }
        ];

        if(notes){
            $.each(notes,function(i,n){
                var flag=false;
                $.each(groups,function(ii,nn){
                    if(flag==false){
                        if(nn.check(n)){
                            //alert(n);
                            nn.notes.push(n);
                            flag=true;
                        }
                    }
                });
            });
        }
        return groups;
    };

    this.get_avatar=function(email,size){
      if (!size) size = 48;
        var av='/images/contacts/people_logo.jpg';

       try{
           var _email = email;
           var avatar=null;
           av = 'http://www.gravatar.com/avatar/'
           +$.md5(_email)
           +'?s='+size+'&d=identicon';
       }catch(e){
           av='/images/contacts/people_logo.jpg';
       }
        return av;
    };

    //  Render partial
    
};