/*
 * Copyright 2007,2008,2009 Limedrive Studio.
 *
 * Urheberrechtlich geschützt, für Lizenzierungskonditionen
 * kontaktieren Sie uns bitte.
 *
 */

/* within the context of this script 'player' refers to a draggable. */

MysticDraggable = function(id, sGroup, config) {
    MysticDraggable.superclass.constructor.apply(this, arguments);
    this.initDraggable(id, sGroup, config);
};

MysticDroppable = function(id, sGroup, config) {
    MysticDroppable.superclass.constructor.apply(this, arguments);
    this.initDroppable(id, sGroup, config);
};

YAHOO.extend(MysticDroppable, YAHOO.util.DDTarget, {

    TYPE: "Droppable",

    initDroppable: function(id, sGroup, config) {
      if (config) {
          this.slotindex = config.slotindex; 
          this.onDnd = config.onDnd; 
          this.containerId = config.containerId;
      }

    }
});

YAHOO.extend(MysticDraggable, YAHOO.util.DD, {

    TYPE: "Draggable",

    initDraggable: function(id, sGroup, config) {
        if (!id) { 
            return; 
        }

        var el = this.getDragEl()
        //YAHOO.util.Dom.setStyle(el, "borderColor", "transparent");
        //YAHOO.util.Dom.setStyle(el, "opacity", 0.76);

        // specify that this is not currently a drop target
        this.isTarget = false;

        this.originalStyles = [];

        this.type = MysticDraggable.TYPE;
        if (config) {
          this.slot = config.initialDroppable;
          config.initialDroppable.player = this;
          YAHOO.log("initial droppable for " + id + " is " + this.slot.id);
          //console.log("init draggable %s with tooltip %s", this.id, config.tooltip);
          this.tooltip = config.tooltip; 
          this.largePic = config.largePic;
          this.smallPic = config.smallPic;
        }

        this.startPos = YAHOO.util.Dom.getXY( this.getEl() );
        YAHOO.log(id + " startpos: " + this.startPos, "info", "example");
    },

    startDrag: function(x, y) {
        YAHOO.log(this.id + " startDrag", "info", "example");
        var Dom = YAHOO.util.Dom;

        var dragEl = this.getDragEl();
        var clickEl = this.getEl();

        this.disableTooltip();

        if (this.slot.groups["equipment"])
          this.getEl().src = this.smallPic;

        //YAHOO.util.Dom.setStyle(this.getEl(), "z-index", 99999);

        dragEl.innerHTML = clickEl.innerHTML;
        dragEl.className = clickEl.className;

        Dom.setStyle(dragEl, "color",  Dom.getStyle(clickEl, "color"));
        Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));

        Dom.setStyle(clickEl, "opacity", 1);

        var targets = YAHOO.util.DDM.getRelated(this, true);
        YAHOO.log(targets.length + " targets", "info", "example");
        for (var i=0; i<targets.length; i++) {
          var targetEl = new YAHOO.util.Element(this.getTargetDomRef(targets[i]));

          if (targets[i].player && this.slot
              && !this.isLegalTarget(targets[i].player, this.slot))
          {
            continue;
          }

          targetEl.addClass("target");
        }

        this.origZ = this.getEl().style.zIndex;
        this.getEl().style.zIndex = 999;
    },

    isLegalTarget: function (draggable, target) {
      if (target.player && this.slot) {
        // no merchant swapping
        if (draggable.groups["sell"] && target.groups["sell"])
          return false;
        if (draggable.groups["buy"] && target.groups["buy"])
          return false;
      }

      return YAHOO.util.DDM.isLegalTarget(draggable, target);
    },

    getTargetDomRef: function(oDD) {
        if (oDD.player) {
            return oDD.player.getEl();
        } else {
            return oDD.getEl();
        }
    },

    onDragDrop: function(e, id) {
        var swap = false;
        var Dom = YAHOO.util.Dom;
        // get the drag and drop object that was targeted
        var source = this.slot;
        var target;

        if ("string" == typeof id) {
            target = YAHOO.util.DDM.getDDById(id);
        } else {
            target = YAHOO.util.DDM.getBestMatch(id);
        }

        YAHOO.log("processing DND from " + this.slot.id + " to " + target.id
            + ", draggable is " + this.id + ". target slot has the following "
            + "draggable in it: " + target.player, "info", "onDragDrop");

        var el = this.getEl();

        // check if the slot has a player in it already
        if (target.player) {
            // check if the dragged player was already in a slot (always true right now)
            if (this.slot) {
                // check to see if the player that is already in the
                // slot can go to the slot the dragged player is in
                // YAHOO.util.DDM.isLegalTarget is a new method
                if (this.isLegalTarget(target.player, this.slot)) {
                    if (this.slot != target) { // act only on new slot
                      swap = true;


                      if (this.slot.groups["equipment"] && target.player.largePic)
                        target.player.getEl().src = target.player.largePic;
                      else
                        target.player.getEl().src = target.player.smallPic;

                      if (target.player.tooltip && this.slot.containerId)
                        target.player.tooltip.itemContainerId = this.slot.containerId;

                      this.slot.getEl().appendChild(target.player.getEl());
                      YAHOO.util.DDM.moveToEl(target.player.getEl(), this.slot.getEl());

                      if (target.player.slot.groups["equipment"]
                          || target.player.slot.groups["inventory"]) {
                          // swapped item comes from equipment slot and thus
                          // has absolute positioning; reset it.
                          target.player.getEl().style.position = 'static';
                          //this.slot.getEl().style.position = 'static';
                      }

                      this.slot.player = target.player;
                      target.player.slot = this.slot;

                    }
                } else {
                    // cancel op, similar to invalid drop
                    YAHOO.util.DragDropMgr.moveToEl(this.getEl(), this.slot.getEl());
                    this.resetTargets();
                    return;
                }
            } else {
                // the player in the slot will be moved to the dragged
                // players start position
                target.player.slot = null;
                YAHOO.util.DDM.moveToEl(target.player.getEl(), el);
            }
        } else {
            // Move the player into the empty slot
            // I may be moving off a slot so I need to clear the player ref
            if (this.slot) {
                this.slot.player = null;
                YAHOO.log("clearing this.slot slot " + this.slot.id, "info", "onDragDrop");
            }
        }


        if (target.groups["equipment"] && this.largePic)
          this.getEl().src = this.largePic;
        else
          this.getEl().src = this.smallPic;

        target.getEl().appendChild(this.getEl());
        YAHOO.util.DDM.moveToEl(el, target.getEl());
        this.resetTargets();

        if (this.slot != target)
        {
          /*
          Array.prototype.remove=function(s){
              for(i=0;i<this .length;i++){
                    if(s==this[i]) this.splice(i, 1);
                      }
          }
          */

          //console.log("target groups: %s, src groups: %s", target.groups, this.slot.groups);
          //console.dir(target.groups);
          if (this.groups["sell"]) { this.removeFromGroup('sell');
                                         /*this.addToGroup("buy"); // itemid change */
                                          }
          else if (this.groups["buy"]) { this.removeFromGroup('buy'); 
                                         /*this.addToGroup("sell"); // disabled right now because the itemid changes */
                                          }
        }
        //console.dir(this.groups);

        //console.log("this.getEl: %s, parent: %s");
        var usableTarget = false;
        if (target.groups["usable"]) {
          usableTarget = true;
          this.getEl().parentNode.removeChild(this.getEl());
        }

        //  console.log("tooltip: %s, targetcid: %s, largepic: %s",
        //      this.tooltip, target.containerId, this.largePic);
        if (this.tooltip && target.containerId)
          this.tooltip.itemContainerId = target.containerId;

        originalSlot = this.slot;
        originalPlayer = this.slot.player;

        this.slot = target;
        if (!usableTarget) // don't hog the use droppable
          this.slot.player = this;

        if (typeof(leftHand) != "undefined"
            && !(this.slot == leftHand && target == rightHand)
            && !(this.slot == rightHand && target == leftHand))
          // unless moved from one hand to another
          reconfigureHandGroups();

//        target.onDnd(Object.toJSON(originalSlot.containerId), originalSlot.slotindex,
//                     Object.toJSON(target.containerId), target.slotindex,
//                     this.id, swap);
        target.onDnd(Object.toJSON(originalSlot.groups), originalSlot.slotindex,
                     Object.toJSON(target.groups), target.slotindex,
                     this.id, swap);

    },

    disableTooltip: function() {
                 if (this.tooltip) {
                   this.tooltip.cfg.setProperty("disabled", true);
                   this.tooltip.hide();
                 }
               },

    endDrag: function(e) {
        // reset the linked element styles
        YAHOO.util.Dom.setStyle(this.getEl(), "opacity", 1);

        this.resetTargets();

        if (this.tooltip) {
          this.tooltip.cfg.setProperty("disabled", false);
        }

        this.getEl().style.zIndex = this.origZ; 
    },

    resetTargets: function() {

        // reset the target styles
        var targets = YAHOO.util.DDM.getRelated(this, true);
        for (var i=0; i<targets.length; i++) {
          var targetEl = new YAHOO.util.Element(this.getTargetDomRef(targets[i]));
          targetEl.removeClass("target");
        }
    },

    onInvalidDrop: function(e) {
                if (this.slot.groups["equipment"])
                  this.getEl().src = this.largePic;

                new YAHOO.util.Motion( 
                    this.id, { 
                        points: { 
                            to: YAHOO.util.Dom.getXY(this.slot.getEl())
                        }
                    }, 
                    0.7, 
                    YAHOO.util.Easing.easeOut 
                ).animate();
                //YAHOO.util.DragDropMgr.moveToEl(this.getEl(), this.slot.getEl());
    },

    onDragOver: function(e, id) {
    },

    tooltip: null,

    onDrag: function(e, id) {
              //console.log("ondrag for %s (this: %s, tooltip: %s)", id, this, this.tooltip);
               //  console.dir(document.getElementById(this.tooltip));
    },

});

var slots = [], players = [],
    Event = YAHOO.util.Event, DDM = YAHOO.util.DDM;

Event.onDOMReady(function() { 
    DDM.mode = YAHOO.util.DragDropMgr.POINT;
});

function reconfigureHandGroups()
{
  //console.log("reconfiguring hand groups");

  var hands = [rightHand,leftHand];

  //console.debug("hands: %o", hands);

  for (var i=0;i<hands.length;i++) {
    var thisHand = hands[i], otherHand = hands[1-i],
        thisWeapon = thisHand.player, otherWeapon = otherHand.player;

    thisHand.removeFromGroup('shield');
    thisHand.removeFromGroup('single-handed-weapon');
    thisHand.removeFromGroup('double-handed-weapon');

    //console.debug("this: %o, other: %o", thisWeapon, otherWeapon);

    if (otherWeapon && otherWeapon.groups["double-handed-weapon"])
      null;
    else
    if (otherWeapon && otherWeapon.groups["shield"])
      thisHand.addToGroup("single-handed-weapon");
    else
    if (otherWeapon && otherWeapon.groups["single-handed-weapon"])
      thisHand.addToGroup("shield");
    else
    {
      thisHand.addToGroup("shield");
      thisHand.addToGroup("single-handed-weapon");
      thisHand.addToGroup("double-handed-weapon");
    }
  }

  //console.debug("groups after: left: %o, right: %o", leftHand.groups, rightHand.groups);
}

function disableSelection(element) {
    element.onselectstart = function() {
        return false;
    };
    element.unselectable = "on";
    element.style.MozUserSelect = "none";
    element.style.cursor = "default";
}
