﻿function Turret() {
}

Turret.prototype.init = function(point, name) {
    this.level = 1;
    this.point = point;
    this.name = name;
    this.onChangeIcon = new YAHOO.util.CustomEvent("onChangeIcon", this);
    this.onAttack = new YAHOO.util.CustomEvent("onAttack", this);
    this.targets = new Array(); //Stores an array of targets within range
    this.curCycle = 0;
    this.maxCycle = 100;
    this.isAttacking = false;
    this.curFaceDir = "nw";
    this.changedAttackStatus = false;
    this.overlayMarker = new GMarker(this.point, { icon: Turret.overlayIcon, title: name, clickable: false, zIndexProcess: function(){return -50;} });
}

//Invisible overlay static properties
var overlayIcon = new GIcon(G_DEFAULT_ICON);
overlayIcon.image = "";
overlayIcon.shadow = "";
Turret.overlayIcon = overlayIcon;

Turret.prototype.faceTarget = function() {
    var point = this.targets[0].point();
    var latDir;
    var lngDir;

    if (point.lat() <= this.point.lat())
        latDir = "s";
    else
        latDir = "n"

    if (point.lng() <= this.point.lng())
        lngDir = "w";
    else
        lngDir = "e";

    var newDir = latDir + lngDir;

    //Only change the marker if the direction or the firing action changes
    if (newDir != this.curFaceDir || this.changedAttackStatus) {
        this.curFaceDir = latDir + lngDir;
        this.setMarker();
        this.changedAttackStatus = false;
    }
}

//this function is in order to track when the turret has started/stopped attacking in order to sync the animation/marker icon
Turret.prototype.setAttacking = function(attackStatus) {
    if(!this.isAttacking == attackStatus)
    {
        this.changedAttackStatus = true;
        this.isAttacking = attackStatus;
    }
}

////////////////////////RUN
Turret.prototype.run = function() {
		if (this.targets.length > 0) {
			if (!this.isAttacking) 
				this.attackTargets();
			else 
				this.setAttacking(false);
			this.faceTarget();
		}
		else {
			this.setAttacking(false);
			if (this.curFaceDir != "nw" || this.changedAttackStatus) {
				this.curFaceDir = "nw";
				this.setMarker();
			}
		}
}