Enemy flips upside down when i walk close.

My current AI script lets the enemy walk, attack, and play animations. Problem is, when i walk close to him, he flips so his feet are in the player’s camera. How do i fix this? If you need a video to help figure out the problem i can post one.

var Distance;
var Target : Transform;
var lookAtDistance = 25.0;
var chaseRange = 15.0;
var attackRange = 1.5;
var moveSpeed = 5.0;
var Damping = 6.0;
var attackRepeatTime = .5;
var SelectObjectThatHasThisScript : Transform;
var TheDammage = 40;
var walkanimation : boolean = true;
var runanimation : boolean = true;
var attackanimation : boolean = true;

private var attackTime : float;

var controller : CharacterController;
var gravity : float = 20.0;
private var MoveDirection : Vector3 = Vector3.zero;

function Start ()
{
	attackTime = Time.time;
}

function Update ()
{
	if(RespawnMenuV2.playerIsDead == false)
	{
		Distance = Vector3.Distance(Target.position, transform.position);
		
		if (Distance < lookAtDistance)
		{
			lookAt();
			walkanimation = true;
			runanimation = false;
			attackanimation = false;
		}
		
		if (Distance > lookAtDistance)
		{
			renderer.material.color = Color.green;
		}
		
		if (Distance < attackRange)
		{
			attack();
			walkanimation = false;
			runanimation = false;
			attackanimation = true;
		}
		else if (Distance < chaseRange)
		{
			chase ();
			walkanimation = false;
			runanimation = true;
			attackanimation = false;
		}
	}
}

function lookAt ()
{
	if (walkanimation == true){
	SelectObjectThatHasThisScript.animation.Play("WalkAim");
	}
	renderer.material.color = Color.yellow;
	var rotation = Quaternion.LookRotation(Target.position - transform.position);
	transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
}

function chase ()
{
	if (runanimation == true){
	SelectObjectThatHasThisScript.animation.Play("Run");
	}
	renderer.material.color = Color.red;
	
	moveDirection = transform.forward;
	moveDirection *= moveSpeed;
	
	moveDirection.y -= gravity * Time.deltaTime;
	controller.Move(moveDirection * Time.deltaTime);
}

function attack ()
{
	if (attackanimation == true){
	SelectObjectThatHasThisScript.animation.Play("StandingFire");
	}
	if (Time.time > attackTime)
	{
		
		Target.SendMessage("ApplyDammage", TheDammage);
		Debug.Log("The Enemy Has Attacked");
		attackTime = Time.time + attackRepeatTime;
	}
}

function ApplyDammage ()
{
	chaseRange += 30;
	lookAtDistance += 40;
}

This could be because at some point your object is too close to its target.
Try replacing if (Distance < lookAtDistance) by if (Distance < lookAtDistance && Distance >= attackRange)at line 32.

I had this error too on a lower scale, just set a distance limit on up axis(i forgot if its x or y or z sorry :P) for it too be looking at the target object.