/*
 * Copyright (c) 1998-2009 TeamDev Ltd. All Rights Reserved.
 * Use is subject to license terms.
 */


// ================================== PUBLIC API METHODS

function q_showPopupLayer(popupId) {
  if (!popupId)
    throw "q_showPopupLayer: popupLayer's clientId must be passed as a parameter";
  var popup = document.getElementById(popupId);
  if (!popup)
    throw "q_showPopupLayer: Invalid clientId passed - no such component was found: " + popupId;
  popup.show();
}

function q_showPopupLayerAtXY(popupId, x, y) {
  if (!popupId)
    throw "q_showPopupLayerAtXY: popupLayer's clientId must be passed as a parameter";
  var popup = document.getElementById(popupId);
  if (!popup)
    throw "q_showPopupLayerAtXY: Invalid clientId passed - no such component was found: " + popupId;
  popup.showAtXY(x, y);
}

function q_setPopupLayerLeft(popupId, x) {
  if (!popupId)
    throw "q_setPopupLayerLeft: popupLayer's clientId must be passed as a parameter";
  var popup = document.getElementById(popupId);
  if (!popup)
    throw "q_setPopupLayerLeft: Invalid clientId passed - no such component was found: " + popupId;
  popup.setLeft(x);
}

function q_setPopupLayerTop(popupId, y) {
  if (!popupId)
    throw "q_setPopupLayerTop: popupLayer's clientId must be passed as a parameter";
  var popup = document.getElementById(popupId);
  if (!popup)
    throw "q_setPopupLayerTop: Invalid clientId passed - no such component was found: " + popupId;
  popup.setTop(y);
}

function q_hidePopupLayer(popupId) {
  if (!popupId)
    throw "q_hidePopupLayer: popupLayer's clientId must be passed as a parameter";
  var popup = document.getElementById(popupId);
  if (!popup)
    throw "q_hidePopupLayer: Invalid clientId passed - no such component was found: " + popupId;
  popup.hide();
}

function q_showPopupLayerCentered(popupId) {
  if (!popupId)
    throw "q_setPopupLayerTop: popupLayer's clientId must be passed as a parameter";
  var popup = document.getElementById(popupId);
  if (!popup)
    throw "q_hidePopupLayer: Invalid clientId passed - no such component was found: " + popupId;
  popup.showCentered();
}

// ================================== END OF PUBLIC API METHODS

var POPUP_FIRST_EXTERNAL_ANCHOR_SUFFIX = "::firstExternalAnchor";
var POPUP_LAST_EXTERNAL_ANCHOR_SUFFIX = "::lastExternalAnchor";
var POPUP_PRE_FIRST_INTERNAL_ANCHOR_SUFFIX = "::preFirstInternalFocusableAnchor";
var POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX = "::firstInternalFocusableAnchor";
var POPUP_LAST_INTERNAL_ANCHOR_SUFFIX = "::lastInternalFocusableAnchor";

function q__initPopupLayer(id, left, top, width, height, rolloverStyle, hidingTimeout, draggable, isAjaxRequest) {
  var popup = q__getControl(id);

  q__initIETransparencyWorkaround(popup);

  popup._visibleField = q__getControl(popup.id + "::visible");
  popup._leftField = q__getControl(popup.id + "::left");
  popup._topField = q__getControl(popup.id + "::top");
  popup.style.display = q__getElementStyleProperty(popup, "display");

  popup.blockingLayer = q__getControl(popup.id + "::blockingLayer");

//  if (popup.blockingLayer) {
  //      // This is needed for situations when blocking layer with style="filter:alpha(opacity: 50)" is positioned inside
  //    // <td> element of <table>. Under IE quirks mode this situation will cause the filter not to be applied. So we
  //    // need to move blocking layer outside of <table> tag.
  //    q__addLoadEvent(function() {
  //      var newParent = q__getDefaultAbsolutePositionParent();
  //      newParent.appendChild(popup.blockingLayer);
  //    });
  //  }


  //  popup.anchorField = q__getControl(popup.id + "_anchor");

  popup._draggable = draggable;

  popup._rolloverStyleNames = rolloverStyle;

  popup._onmousedown = popup.onmousedown;
  popup._onmouseup = popup.onmouseup;
  popup._onmousemove = popup.onmousemove;
  popup._onmouseover = popup.onmouseover;
  popup._onmouseout = popup.onmouseout;

  // --------------- Popup functions start
  popup.setLeft = function (left) {
    if (left == null || left == undefined || isNaN(left))
      throw "popupLayer.setLeft: the integer number should be passed as a parameter, but the following value was passed: " + left;
    popup.style.left = left + "px";
    if (popup._ieTransparencyControl)
      popup._ieTransparencyControl.style.left = left + "px";

    popup._leftField.value = left;
    popup.left = left;
    if (popup._positionChanged)
      popup._positionChanged();
  }

  popup.setTop = function (top) {
    if (top == null || top == undefined || isNaN(top))
      throw "poupLayer.setTop: the integer number should be passed as a parameter, but the following value was passed: " + top;
    popup.style.top = top + "px";
    if (popup._ieTransparencyControl)
      popup._ieTransparencyControl.style.top = top + "px";

    popup._topField.value = top;
    popup.top = top;
    if (popup._positionChanged)
      popup._positionChanged();
  }

  popup.showCentered = function() {
    this.show();
    q__centerPopup(this);
  }

  popup.showByElement = function(element, horizAlignment, vertAlignment, horizDistance, vertDistance) {
    this.style.visibility = "hidden";
    this.show();
    setTimeout(function() {
      q__alignPopupByElement(popup, element, horizAlignment, vertAlignment, horizDistance, vertDistance);
      popup.style.visibility = "";
    }, 1);
  }

  popup.show = function () { // todo: this overrides popup.show declared in popup.js, merge as much functionality in popupLayer.js and popup.js as possible
    if (popup.isVisible()) return;
    popup.style.display = "block";
    q__addIETransparencyControl(popup);
    if (popup.blockingLayer) {
      var body = document.getElementsByTagName("body")[0];
      var firstExternalAnchor = null;
      var firstExternalAnchorOld = document.getElementById(popup.id + POPUP_FIRST_EXTERNAL_ANCHOR_SUFFIX);

      if (!firstExternalAnchorOld) {
        firstExternalAnchor = q__createHiddenFocusElement();
      }
      else {
        firstExternalAnchor = firstExternalAnchorOld;
      }
      firstExternalAnchor.id = popup.id + POPUP_FIRST_EXTERNAL_ANCHOR_SUFFIX;
      firstExternalAnchor.onfocus = function() {
        var el = document.getElementById(popup.id + POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX);
        el.focus();
      };

      var firstDocEl = body.firstChild;
      body.insertBefore(firstExternalAnchor, firstDocEl);

      var lastExternalAnchor = null;
      var lastExternalAnchorOld = document.getElementById(popup.id + POPUP_LAST_EXTERNAL_ANCHOR_SUFFIX);
      if (!lastExternalAnchorOld) {
        lastExternalAnchor = q__createHiddenFocusElement();
      }
      else {
        lastExternalAnchor = lastExternalAnchorOld;
      }
      lastExternalAnchor.id = popup.id + POPUP_LAST_EXTERNAL_ANCHOR_SUFFIX;
      lastExternalAnchor.onfocus = function() {
        var el = document.getElementById(popup.id + POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX);
        el.focus();
      };
      body.appendChild(lastExternalAnchor);

      var firstInternalAnchor = q__createHiddenFocusElement();
      firstInternalAnchor.id = popup.id + POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX;
      var firstPopupEl = popup.firstChild;
      popup.insertBefore(firstInternalAnchor, firstPopupEl);
      var preFirstInternalAnchor = q__createHiddenFocusElement();
      preFirstInternalAnchor.id = popup.id + POPUP_PRE_FIRST_INTERNAL_ANCHOR_SUFFIX;
      preFirstInternalAnchor.onfocus = function() {
        var el = document.getElementById(popup.id + POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX);
        el.focus();
      };
      popup.insertBefore(preFirstInternalAnchor, firstInternalAnchor);
      firstInternalAnchor.focus();

      var lastInternalAnchor = q__createHiddenFocusElement();
      lastInternalAnchor.id = popup.id + POPUP_LAST_INTERNAL_ANCHOR_SUFFIX;
      lastInternalAnchor.onfocus = function () {
        var el = document.getElementById(popup.id + POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX);
        el.focus();
      };
      popup.appendChild(lastInternalAnchor);
    }

    if (popup.anchorElement != undefined) {
      q__popup_moveToAnchor(popup);
    }
    //    q__hideControlsUnderPopup(this);

    if (popup.blockingLayer) { //modal popup
      //todo: rework blocking layer creation to make <body> its parent (to prevent other controls in table cell, when this cell is big, moving up or down)
      //todo: jsfc-1497
      popup.blockingLayer.style.display = "";

      document._q_activeModalLayer = popup.blockingLayer;
      q__popupLayer_resizeModalLayer();
      if (q__simulateFixedPosForBlockingLayer()) {
        var prnt = popup.offsetParent;
        if (prnt) {
          prnt = prnt.offsetParent;
        }
        var prntPos = prnt != null ? q__getElementPos(prnt) : {left: 0, top: 0};
        var parentLeft = prntPos.left;
        var parentTop = prntPos.top;
        popup.blockingLayer.style.left = (document.body.scrollLeft - parentLeft) + "px";
        popup.blockingLayer.style.top = (document.body.scrollTop - parentTop) + "px";
        q__addEventHandler(window, "resize", q__popupLayer_resizeModalLayer);
        q__addEventHandler(window, "scroll", q__popupLayer_alignModalLayer);
        q__popupLayer_alignModalLayer();
      } else {
        popup.blockingLayer.style.left = "0px";
        popup.blockingLayer.style.top = "0px";
        popup.blockingLayer.style.position = "fixed";
        window.addEventListener("resize", q__popupLayer_resizeModalLayer, true);
      }

    }
    popup._visibleField.value = "true";
    if (popup.onshow) {
      popup.onshow();
    }
    if (popup.hideTimer) {
      clearTimeout(popup.hideTimer);
    }

    /*
        if (q__isExplorer()) {
          popup.setLeft(popup.startX);
          popup.setTop(popup.startY);
        }
    */

    if (popup._hidingTimeout && popup._hidingTimeout > 0) {
      popup.hideTimer = setTimeout(function() {
        popup.hide()
      }, popup._hidingTimeout);
    }
    q__repaintAreaForOpera(popup, true);
    if (popup._afterShow)
      popup._afterShow();
  }

  popup.hide = function () {
    if (!popup.isVisible()) return;
    q__removeIETransparencyControl(popup);
    if (popup.blockingLayer) {
      var body = document.getElementsByTagName("body")[0];
      var firstExtAnc = document.getElementById(popup.id + POPUP_FIRST_EXTERNAL_ANCHOR_SUFFIX);
      if (firstExtAnc) {
        body.removeChild(firstExtAnc);
      }
      var lastExtAnc = document.getElementById(popup.id + POPUP_LAST_EXTERNAL_ANCHOR_SUFFIX);
      if (lastExtAnc) {
        body.removeChild(lastExtAnc);
      }
      var el = document.getElementById(popup.id + POPUP_FIRST_INTERNAL_ANCHOR_SUFFIX);
      if (el) {
        popup.removeChild(el);
      }
      el = document.getElementById(popup.id + POPUP_LAST_INTERNAL_ANCHOR_SUFFIX);
      if (el) {
        popup.removeChild(el);
      }
      el = document.getElementById(popup.id + POPUP_PRE_FIRST_INTERNAL_ANCHOR_SUFFIX);
      if (el) {
        popup.removeChild(el);
      }
    }

    //    q__unhideControlsUnderPopup(this);
    popup.style.display = "none";
    if (popup.onhide) {
      popup.onhide();
    }
    if (popup.hideTimer) {
      clearTimeout(popup.hideTimer);
    }
    popup._visibleField.value = "false";

    if (popup.blockingLayer) {
      popup.blockingLayer.style.display = "none";
      if (q__simulateFixedPosForBlockingLayer()) {
        q__removeEventHandler(window, "scroll", q__popupLayer_alignModalLayer);
        q__removeEventHandler(window, "resize", q__popupLayer_resizeModalLayer);
      } else {
        document.removeEventListener("resize", q__popupLayer_resizeModalLayer, true);
      }
      if (q__isOpera()) {
        document.body.style.visibility = "hidden";
        document.body.style.visibility = "visible";
      }
    }
    q__repaintAreaForOpera(document.body, true);
    if (popup._afterHide)
      popup._afterHide();
  }

  popup.isVisible = function () {
    return popup.style.display != "none";
  }

  if (rolloverStyle != null) {
    popup.onmouseover = function (e) {
      if (popup._onmouseover) {
        popup._onmouseover(e);
      }
      q__appendClassNames(popup, [popup._rolloverStyleNames]);
      q__repaintAreaForOpera(popup, true);
    }

    popup.onmouseout = function (e) {
      if (popup._onmouseout) {
        popup._onmouseout(e);
      }
      q__excludeClassNames(popup, [popup._rolloverStyleNames]);
      q__repaintAreaForOpera(popup, true);
    }
  } else {
    popup.onmouseover = function (e) {
      if (popup._onmouseover) {
        popup._onmouseover(e);
      }
    }

    popup.onmouseout = function (e) {
      if (popup._onmouseout) {
        popup._onmouseout(e);
      }
    }
  }

  popup.showAtXY = function (x, y) {
    popup.setLeft(x);
    popup.setTop(y);
    popup.show();
  }

  popup.getAnchorElement = function () {
    return popup.anchorElement;
  }
  popup.attachToElement = function (elt, anchorX, anchorY) {
    popup.anchorElement = elt;
    popup.anchorX = anchorX;
    popup.anchorY = anchorY;

    q__popup_moveToAnchor(popup);

    //    if (elt.id) {
    //      popup.anchorField.value = elt.id;
    //    }
  }

  popup.onmousedown = function (e) {
    if (popup._onmousedown) {
      popup._onmousedown(e);
    }
    if (popup._draggable) {
      q__startDragAndDrop(e, popup);
    }
  }
  popup.onmouseup = function (e) {
    if (popup._onmouseup) {
      popup._onmouseup(e);
    }
  }
  popup.onmousemove = function (e) {
    if (popup._onmousemove) {
      if (!popup._draggingInProgress) {
        popup._onmousemove(e);
      }
    }
  }

  // --------------- Popup functions end

  popup.left = left;
  if (left != null)
    try {
      popup.setLeft(left);
    } catch (e) {
      q__logError("Invalid value of the 'left' attribute of PopupLayer: \"" + left + "\" ; it must be an integer value ; original error: " + e.message);
      throw e;
    }

  popup.top = top;
  if (top != null)
    try {
      popup.setTop(top);
    } catch (e) {
      q__logError("Invalid value of the 'top' attribute of PopupLayer: \"" + top + "\" ; it must be an integer value ; original error: " + e.message);
      throw e;
    }

  if (width != null)
    try {
      popup.style.width = width;
    } catch (e) {
      q__logError("Invalid value of the 'width' attribute of PopupLayer: \"" + width + "\" ; it must be a valid CSS declaration like \"100px\" ; original error: " + e.message);
      throw e;
    }

  if (height != null)
    try {
      popup.style.height = height;
    } catch (e) {
      q__logError("Invalid value of the 'height' attribute of PopupLayer: \"" + height + "\" ; it must be a valid CSS declaration like \"100px\" ; original error: " + e.message);
      throw e;
    }

  popup._hidingTimeout = hidingTimeout;

  q__addLoadEvent(function () {
    if (popup._visibleField.value == "true")
      popup.show();
  }, isAjaxRequest);

  //  if(popup.anchorField.value && popup.anchorField.value != ""){
  //    var elt = q__getControl(popup.anchorField.value);
  //    if(elt){
  //      popup.attachToElement(elt, "center", "middle");
  //    }
  //  }
}

function q__simulateFixedPosForBlockingLayer() {
  return q__isExplorer() /* ie doesn't support fixed pos */ ||
         q__isMozillaFF() || q__isSafari3AndLate() /*todo:check whether q__isSafari3AndLate check is really needed (it was added by mistake)*/ /* mozilla's blocking layer hides cursor of text-field in fixed-pos popup-layer (JSFC-1930) */;
}

// -- Standalone popup functions

function q__popup_moveToAnchor(popup) {
  var elt = popup.anchorElement;
  var anchorX = popup.anchorX;
  var anchorY = popup.anchorY;

  if (anchorX == undefined || anchorX == null) {
    anchorX = "left";
  }
  if (anchorY == undefined || anchorY == null) {
    anchorY = "top";
  }

  var eltRect = q__getElementBorderRectangle(elt);
  if (anchorX == "right") {
    popup.setLeft(eltRect.getMaxX());
  } else if (anchorX == "center") {
    popup.setLeft(eltRect.getMinX() + eltRect.width / 2);
  } else { // left
    popup.setLeft = eltRect.getMinX();
  }

  if (anchorY == "bottom") {
    popup.setTop(eltRect.getMaxY());
  } else if (anchorY == "middle") {
    popup.setTop(eltRect.getMinY() + eltRect.height / 2);
  } else { // top
    popup.setTop(eltRect.getMinY());
  }
}

function q__getLeftBodyMargin() {
  return q__getNumericStyleProperty(document.body, "margin-left");
}

function q__getTopBodyMargin() {
  return q__getNumericStyleProperty(document.body, "margin-top");
}

function q__popupLayer_alignModalLayer() {
  var modalLayer = document._q_activeModalLayer;
  var scrollPos = q__getPageScrollPos();
  var prnt = modalLayer.offsetParent;
  var parentPos = prnt != null && prnt.nodeName != "HTML" && prnt.nodeName != "BODY"
          ? q__getElementPos(prnt)
          : {left: 0, top: 0};
  var parentLeft = parentPos.left;
  var parentTop = parentPos.top;
  // the comments below are caused by JSFC-2030

  modalLayer.style.left = (/*q__getLeftBodyMargin() + */ scrollPos.x - parentLeft) + "px";
  modalLayer.style.top = (/*q__getTopBodyMargin() + */ scrollPos.y - parentTop) + "px";
  q__popupLayer_resizeModalLayer();
}

function q__popupLayer_resizeModalLayer() {
  var modalLayer = document._q_activeModalLayer;

  var visibleAreaSize = q__getVisibleAreaRectangle();

  modalLayer.style.width = visibleAreaSize.width + "px";
  modalLayer.style.height = visibleAreaSize.height + "px";
}

function q__getCoordsForCenteredPopup(popup) {
  var visibleAreaSize = q__getVisibleAreaSize();
  //var parentToCalculateScrollOffset = q__getParentToCalculateScrollOffset(popup);
  //var prntPos = q__getElementPos(parentToCalculateScrollOffset);
  var x = visibleAreaSize.width / 2 - popup.offsetWidth / 2 + q__getPageScrollPos().x;
  var y = visibleAreaSize.height / 2 - popup.offsetHeight / 2 + q__getPageScrollPos().y;
  return {x : x, y : y};
}

function q__centerPopup(popup) {
  var coords = q__getCoordsForCenteredPopup(popup);
  popup.setLeft(coords.x);
  popup.setTop(coords.y);
}


function q__getParentToCalculateScrollOffset(popup) {
  var parentToCalculate = popup.offsetParent;
  if (!parentToCalculate) {
    parentToCalculate = document.body;
  }
  return parentToCalculate;
}


//AUTO GENERATED CODE

window['q_loadedLibrary:/qk_internalResource/teamdev/jsf/renderkit/popuplayer/popupLayer-2.0.js'] = true;