// Author: Dmitry Bystrov http://bikosite.net
// Date: 25.12.2009
// Location: Zaporizhzhya, Ukraine, Eastern Europe

function showPopup(width, height, btn) {
  var pos = getElementPosition(btn);
  
  var A;
  if (self.innerWidth!=undefined) A = [self.innerWidth,self.innerHeight];
  else{
    var D = document.body;
    if (D) A = [D.clientWidth,D.clientHeight];
  }
  
  var left = Math.round((A[0] - width)/2);
  var top = Math.round((A[1] - height)/2);

  if (pos.top > top + height) {
    top = pos.top - height/2;
  }
  
  document.getElementById("album_wrapper").style.width = width + 'px';
  document.getElementById("album_wrapper").style.height = height + 'px';
  document.getElementById("album_wrapper").style.left = left + 'px';
  document.getElementById("album_wrapper").style.top = top + 'px';

  document.getElementById("album_wrapper").style.display='block';
  
  document.onkeypress = getPopupKey; 
}

function closePopup() {
  document.getElementById("album_wrapper").style.display='none';
}

function getPopupKey(e) {
  if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	if (keycode=27) closePopup();
  else {
    key = String.fromCharCode(keycode).toLowerCase();
    
    if(key == 'x'){ closePopup(); }
  }
}

function selectPhoto(id) {
  InsertObhvatData('[photo]' + id + '[/photo]', '');
  closePopup();
}

function selectPhotoThumb(id) {
  InsertObhvatData('[photo_thumb]' + id + '[/photo_thumb]', '');
  closePopup();
}

function InsertObhvatData(startdata, enddata) {
  var r = document.post.message;
  if (!r) {
    alert("Error in set text! No message window..");    
  }
  else {    
    r.focus();
    if (document.selection) {
      var r = document.selection.createRange();
      
      r.text = startdata + r.text + enddata;
      r.select();
    }
    else {
      var start = r.selectionStart;
      var end = r.selectionEnd;
      
      var rs = startdata + r.value.substr(start, end-start) + enddata;
      r.value = r.value.substr(0,start)+rs+r.value.substr(end);
      r.setSelectionRange(end+startdata.length, end+startdata.length);
    }
  }
}

function getElementPosition(elem) {
    
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
    
    var l = 0;
    var t = 0;
    
    while (elem)
    {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}
