var afx_mouseoffset = null;
var afx_drag_obj = null;
var afx_drag_cpy = null;
var afx_img_drop_targets = new Array();
var afx_imglist_drop_targets = new Array();

var afx_current_album = '';

document.onmousemove = afx_drag_move;
document.onmouseup = afx_drag_stop;
document.onmousedown = null;

var afx_req = null;
try
{
  req = new XMLHttpRequest();
}
catch(ms)
{
  try
  {
    req = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(nonms)
  {
    try
    {
      req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(failed)
    {
      req = null;
    }
  }
}  
if( req == null )
{
  alert('Dein Browser unterstützt diese Funktion nicht, sorry.');
}

function afx_add_img_droptarget(elem)
{
  afx_img_drop_targets.push(elem);
}

function afx_add_imglist_droptarget(elem)
{
  afx_imglist_drop_targets.push(elem);
}

function afx_getmouse(target, ev)
{
  ev = ev || window.event;   
  var docpos    = afx_getposition(target);
  var mousepos  = afx_mousecoord(ev);   
  return {x:mousepos.x - docpos.x, y:mousepos.y - docpos.y};
}

function afx_mousecoord(ev)
{
  if(!ev) ev = window.event; 
	var body = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ? window.document.documentElement : window.document.body; 
	return { 
	  x: ev.pageX ? ev.pageX : ev.clientX + body.scrollLeft  - body.clientLeft ,
	  y: ev.pageY ? ev.pageY : ev.clientY + body.scrollTop - body.clientTop
	};
}

function afx_getposition(e)
{
  var left = 0;   
  var top  = 0;   

  while (e.offsetParent)
  {
    left += e.offsetLeft;   
    top  += e.offsetTop;   
    e     = e.offsetParent;   
  }

  left += e.offsetLeft;   
  top  += e.offsetTop;   

  return {x:left, y:top};   
}

function afx_drag_start(ev)
{
  ev = ev || window.event;
  if( ev.preventDefault )
  {
    ev.preventDefault();
  }
  afx_mouseoffset = afx_getmouse(this, ev);
  var oldoffset = afx_getposition(this);
  var elem2 = this.cloneNode(true);
  elem2.onmousedown = afx_drag_start;
  this.parentNode.insertBefore(elem2,this);
  this.style.position = 'absolute';
  this.style.left = oldoffset.x + "px";
  this.style.top =  oldoffset.y + "px";
  afx_drag_obj = this;
  afx_drag_cpy = elem2.cloneNode(true);
  afx_drag_cpy.style.display = 'none';
  afx_drag_cpy.style.position = 'relative';
  afx_drag_cpy.style.top = "0px";
  afx_drag_cpy.style.left = "0px";
  afx_drag_obj.style.opacity  = "0.5";
  afx_drag_obj.style.filter = "alpha(opacity=50)";
  return false;
}

function afx_drag_move(ev)
{
  if( afx_drag_obj == null ) return true;
  document.onmousemove = null;
  ev = ev || window.event;
  var mousepos = afx_mousecoord(ev);
  afx_drag_obj.style.position = 'absolute';
  afx_drag_obj.style.top = mousepos.y - afx_mouseoffset.y + "px";
  afx_drag_obj.style.left = mousepos.x - afx_mouseoffset.x + "px";
  if( ev.preventDefault )
  {
    ev.preventDefault();
  }
  var itarget = 0;
  var show_drag = false;
  while( itarget < afx_imglist_drop_targets.length )
  {
    var elem = afx_imglist_drop_targets[itarget];
    itarget++;
    if( elem )
    {
      var target_pos = afx_getposition(elem);
      var target_width = elem.offsetWidth;
      var target_height = elem.offsetHeight;
      if( mousepos.x >= target_pos.x &&
          mousepos.x <= (target_pos.x+target_width) &&
          mousepos.y >= target_pos.y &&
          mousepos.y <= (target_pos.y+target_height) )
      {
        var after_node = null;
        for(var i=elem.childNodes.length-1; i>=0; i--)
        {
          var node = elem.childNodes[i];
          if( node == afx_drag_cpy ) continue;
          if( node.nodeName == '#text' ) continue;
          var tpos = afx_getposition(node);
          var twidth = node.offsetWidth;
          var theight = node.offsetHeight;
          if( tpos.x + twidth > mousepos.x &&
              tpos.y + theight > mousepos.y )
          {
            after_node = node;
          }
        }
        if( after_node == null )
        {
          elem.appendChild(afx_drag_cpy);
        }
        else
        {
          elem.insertBefore(afx_drag_cpy,after_node);
        }
        afx_drag_cpy.style.width = "40px";
        afx_drag_cpy.style.height = "30px";
        show_drag = true;
      }
    }
    afx_drag_cpy.style.display = show_drag ? 'inline' : 'none';
  }  
  document.onmousemove = afx_drag_move;
  return false;
}

function afx_drag_stop(ev)
{
  if( afx_drag_obj == null ) return true;
  ev = ev || window.event;

  // gucken ob die mouse über dem target ist
  var is_dropped = false;
  for(var i=0;i < afx_img_drop_targets.length; i++ )
  {
    var elem = afx_img_drop_targets[i];
    var mousepos = afx_mousecoord(ev);
    var target_pos = afx_getposition(elem);
    var target_width = elem.offsetWidth;
    var target_height = elem.offsetHeight;
    if( mousepos.x >= target_pos.x &&
        mousepos.x <= (target_pos.x+target_width) &&
        mousepos.y >= target_pos.y &&
        mousepos.y <= (target_pos.y+target_height) )
    {
    	// save state
    	is_dropped = true;
    	var old = elem.src;
    	elem.src = 'gfx/load.gif';
    	if( afx_drag_obj.id && afx_current_album != '' )
    	{
    		var pic_id = afx_drag_obj.id.substr(4);
    		afx_drag_obj.parentNode.removeChild(afx_drag_obj);
  			afx_drag_obj = null;
	    	req.open("GET","qry_alb?a=" + afx_current_album + "&set=" + pic_id);
				req.onreadystatechange = function()
				{
					switch(req.readyState)
					{
						case 4:
						  if( req.status != 200 )
						  {
						  	elem.src = old;
						  }
						  else
					  	{
					  		afx_refill_main(elem,req.responseXML);
					  		//elem.src = 'showpic?t=' + pic_id;
					  	}
						  break;
					}
				};
				req.send(null);
			}
			else
			{
				elem.src = afx_drag_obj.src;
				afx_drag_obj.parentNode.removeChild(afx_drag_obj);
  			afx_drag_obj = null;
			}
    }
  }
  if( !is_dropped )
  {
  	afx_drag_obj.parentNode.removeChild(afx_drag_obj);
  	afx_drag_obj = null;
  }
  return false;
}

function afx_pic_refill(id_alb,xml)
{
	afx_current_album = id_alb;
  var container = document.getElementById('pic_container');
  // remove childnodes
  while( container.hasChildNodes()) container.removeChild(container.lastChild);
  // refill childnodes
  var style_path = xml.getElementsByTagName('afx')[0].attributes.getNamedItem('style').value;
  var pics = xml.getElementsByTagName('pic');
  for(var i=0;i<pics.length;i++)
  {
    var pic = pics[i];
    var pic_id = pic.childNodes[0].firstChild.nodeValue;
    var x = document.createElement('div');
    var item_html = '';
    item_html += '<div class="picwrapper">';
    item_html += '<table><tr><td><img id="pic_' + pic_id + '" src="showpic?t=' + pic_id + '" class="thumb"></td><td style="vertical-align:top;">';
    item_html += '<table class="layout" style="height:100%;background:url(' + style_path + '/pt2.png) repeat-y">';
    item_html += '<tr><td><img src="' + style_path + '/pt1.png" class="pts"/></td></tr>';
    item_html += '<tr><td class="pt2"><a href="view?p=' + pic_id + '" target="_blank" title="Bild anzeigen"><img src="' + style_path + '/pt_show.png" class="ico" style="width:11px;height:9px;"/></a></td></tr>';
    item_html += '<tr><td class="pt2"><a href="#" onclick="afx_pic_delete(' + id_alb + ',' + pic_id +');" title="Bild l&ouml;schen"><img src="' + style_path + '/pt_del.png" style="width:11px;height:9px;"/></a></td></tr>';
    item_html += '<tr><td><img src="' + style_path + '/pt3.png" class="pts"/></td></tr>';
    item_html += '</table>';
    item_html += '</td></tr></table>';
    item_html += '</div>';
    x.innerHTML = item_html;
    container.appendChild(x);
    document.getElementById('pic_' + pic_id).onmousedown = afx_drag_start;
  }
  if( pics.length <= 0 )
  {
    container.innerHTML = '<span class="tiny">derzeit keine Bilder vorhanden</span>';
  }
  var mainpic = document.getElementById('main_pic');
  if( mainpic )
  {
  	afx_refill_main(mainpic,xml);
  }
}

function afx_refill_main(elem,xml)
{
	var style_path = xml.getElementsByTagName('afx')[0].attributes.getNamedItem('style').value;
	var main_pic = xml.getElementsByTagName('album')[0].attributes.getNamedItem('main').value;
	if( main_pic != '' )
	{
		elem.src = 'showpic?t=' + main_pic;
	}
	else
	{
		elem.src = '/' + style_path + "/_empty.png";
	}
}

function afx_pic_unset_main(elem)
{
	req.open("GET","qry_alb?a=" + afx_current_album + "&set=x",true);
  req.onreadystatechange = function()
  {
    switch(req.readyState)
    {
      case 4:
        if( req.status != 200 )
        {
          alert('Fehler bei der Übertragung (' + req.status + ')');
        }
        else
        {
          afx_refill_main(elem,req.responseXML);
        }
        break;
      default:
        break;
    }
  };
  req.send(null);
}

function afx_pic_reload(id_alb)
{
  req.open("GET","qry_alb?a=" + id_alb,true);
  req.onreadystatechange = function()
  {
    switch(req.readyState)
    {
      case 4:
        if( req.status != 200 )
        {
          alert('Fehler bei der Übertragung (' + req.status + ')');
        }
        else
        {
          afx_pic_refill(id_alb,req.responseXML);
        }
        break;
      default:
        break;
    }
  };
  req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  req.send(null);
}

function afx_pic_delete(id_alb,id_pic)
{
  if( window.confirm("Willst du dieses Bild wirklich löschen?") == true )
  {
    req.open("GET","qry_alb?a=" + id_alb + "&del=" + id_pic,true);
    req.onreadystatechange = function()
    {
      switch(req.readyState)
      {
        case 4:
          if( req.status != 200 )
          {
            alert('Fehler bei der Übertragung (' + req.status + ')');
          }
          else
          {
            afx_pic_refill(id_alb,req.responseXML);
          }
          break;
        default:
          break;
      }
    };
    req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    req.send(null);
  }
}

function afx_read_subject(id)
{
	req.open("GET","pipe?m=readen&s=" + id,false);
	req.send(null);
}

function afx_read_board(id)
{
	req.open("GET","pipe?m=readen&b=" + id,false);
	req.send(null);
}
