var opens = new Array();
var timeout;
var timeoutSec = 10000;
var updateStart = false;
var fenid;
var pagestart;


function randomFromTo(from, to){
       return Math.floor(Math.random() * (to - from + 1) + from);
    }

//
function createCookie(name,value,days) {
	Cookies.create(name,value,days);
}

//
function readCookie(name) {
	return Cookies[name];
}

//
function eraseCookie(name) {
	Cookies.erase(name);
}

function updateCookies( id, x, y, id_main ){
	
	var myid = 'chatperso'+id
	
	if( id_main && !isNaN(parseInt(id_main)) && parseInt(id_main) > 0  ){
		eraseCookie( 'chatpersoid' );
		createCookie( 'chatpersoid', id_main,1);
	}
	eraseCookie(myid+'w');
	createCookie(myid+'w', x,1);
	eraseCookie(myid+'h');
	createCookie(myid+'h', y,1);
}

var Cookies = {
	init: function () {
		var allCookies = document.cookie.split('; ');
		for (var i=0;i<allCookies.length;i++) {
			var cookiePair = allCookies[i].split('=');
			this[cookiePair[0]] = cookiePair[1];
		}
	},
	create: function (name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
		this[name] = value;
	},
	erase: function (name) {
		this.create(name,'',-1);
		this[name] = undefined;
	}
};
Cookies.init();

var chatpersos = readCookie( 'chatpersos' );
if( chatpersos ){
	var temp = chatpersos.split('_');
	for( n in temp){
		if( temp[n] && !isNaN(parseInt(temp[n])) && parseInt(temp[n]) > 0  ){
			createCookie( 'chatperso'+temp[n]+'start', '0',1);
			eraseCookie('chatperso'+temp[n]+'start');
		}
	}
}

function updateAjax()
{
	if (updateStart) xajax_update();
	timeout = setTimeout("updateAjax()", timeoutSec);
}

function fensterid( id ){
	fenid = id;
}

function initAjax()
{
	xajax_im();
    updateStart = true;
	timeout = setTimeout("updateAjax()", timeoutSec);
}

function rand_wmax( was ){
//
	 var viewportwidth;
	 var viewportheight;
	 var mwidth = 360;
//
	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

	 if (typeof window.innerWidth != 'undefined')
	 {
	      viewportwidth = window.innerWidth;
	      viewportheight = window.innerHeight;
	 }
	 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

	 else if (typeof document.documentElement != 'undefined'
	     && typeof document.documentElement.clientWidth !=
	     'undefined' && document.documentElement.clientWidth != 0)
	 {
	       viewportwidth = document.documentElement.clientWidth;
	       viewportheight = document.documentElement.clientHeight;
	 }
	 else
	 {
	       viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
	       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	 }
	 
	 var ymax = viewportheight-mwidth;
	 var xmax = viewportwidth-mwidth;
	 
	 if( !was ) return viewportwidth;
	 if ( was == 'width' || was == 'x' ) return viewportwidth;
	 if ( was == 'height' || was == 'y' ) return viewportheight;
	 if ( was == 'wmax' || was == 'xmax' ) return xmax;
	 if ( was == 'ymax' || was == 'hmax' ) return ymax;
}

function rand_delta( ){
	 var c = (Math.floor(Math.random()*11)) % 3;
	 var h = 10*c+c;
	 return h;
}

function rand_min( offset ){
	if ( !offset )
		offset = 0;
	 var c = (Math.floor(Math.random()*11)) % 2;
	 var h = 30+Math.floor(Math.random()*11)+5*Math.floor(Math.random()*11)+c*100 + offset;
	 return h;
}

function rand_max( offset ){
	if ( !offset )
		offset = 0;
//
	 var xmax = rand_wmax( 'wmax' );
	 var c = (Math.floor(Math.random()*11)) % 2;
	 var cc = (Math.floor(Math.random()*11)) % 3;
//
	 var w = offset + cc*100+c*10+30+Math.floor(Math.random()*11)+5*Math.floor(Math.random()*11)+3*Math.floor(Math.random()*11);
	if( w > xmax ){
		w = xmax;
	}
	 return w;
}

function reset_opens(id,mo )
{
	for(n in opens)
	{
		if (document.getElementById('xajax_im_open_' + opens[n]))
		{
			var table = document.getElementById('xajax_im_open_' + opens[n]);
        	/*w = readCookie('chatperso'+opens[n]+'w');
        	if( w ){
        		table.style.left   = w+"pt";
        	}
        	
        	h = readCookie('chatperso'+opens[n]+'h');
        	if( h ){
        		table.style.top   = h+"pt";
        	}*/
        	table.style.zIndex = 900;
		}
	}
	//var open_deep = ;
	var table = document.getElementById('xajax_im_open_' + id);
  	table.style.zIndex = 901;
//
  	if( fenid > 0 && document.getElementById('xajax_im_open_' + fenid ) ){
  		var table = document.getElementById('xajax_im_open_' + fenid);
  		table.style.zIndex = 910+opens.lenth;
  	}
//
  	if( mo != 1 ){
//
  		var h;
  		var w;
  		var main_table;
  		var main_id = readCookie('chatpersoid' );

  		if( main_id ){
  			h = readCookie('chatperso'+main_id+'h');
  			//if( h ) h += rand_delta( );
  			
  			w = readCookie('chatperso'+main_id+'w');
  			//if( w ) w += rand_delta( );
  			
  			main_table = document.getElementById('xajax_im_open_' + id);
		}
  		
  		if( !h || h<1){
  			h = rand_min( 190 );
  			if(main_table){
  				createCookie('chatperso'+main_id+'h', h, 1);
  				table.style.top = h+'pt';
  			}
  		}
  		
  		if( !w || w<1){
  			w = rand_min(500);
  			if(main_table){
  				createCookie('chatperso'+main_id+'w', w, 1);
  				table.style.top = w+'pt';
  			}
  		}
//alert( w + ', ' + main_table);
		//table.style.left = w+'pt';
		//table.style.top = h+'pt';
  	}

//alert(4);

};

function checkrwopen( n_int ){
	var ids = readCookie('chatpersos');
	if(!ids) ids='';
//alert( ids.indexOf( '_'+n_int ) );
//
	if( ids.indexOf( '_'+n_int ) < 0 ){
		eraseCookie('chatpersos');
		createCookie( 'chatpersos', ids+'_'+n_int,1);
	}
}

function append_msg(id, msg)
{
  	var div;
  	if (document.getElementById('xajax_im_msgs_' + id))
  	{
	    div = document.getElementById('xajax_im_msgs_' + id);
	    div.innerHTML+=msg;
		div.scrollTop=div.scrollHeight;
  	}
  	else
  	{
	    xajax_im_open(id);
  	}
};

if (typeof vdrag == 'undefined') {
	var vdrag = true;
}

var Drag = {

    obj : null,
    lastx : null,
    lasty : null,

    init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
    {
//
//alert(" 1 ");
//
		var test;
		var id;
		var h;
		var w;
		
		var starth = randomFromTo(130,160);
		
		
		var startw = document.body.clientWidth -200 + randomFromTo(0,20);
		if (startw > 800) startw = 800  + randomFromTo(0,20);
		if (screen.width < 1000) startw = 600  + randomFromTo(0,20);
		//alert(startw);
//		
        o.onmousedown    = Drag.start;

        //o.hmode            = bSwapHorzRef ? false : true ;
        //o.vmode            = bSwapVertRef ? false : true ;
        //o.vmode            = vdrag ? true : false ;
        
        o.hmode = true;
        o.vmode = true;
        o.root = oRoot && oRoot != null ? oRoot : o ;

//alert( o.root.style.left );

        if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
        if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
        /*
        if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
        if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";
        */

        o.minX    = typeof minX != 'undefined' ? minX : null;
        o.minY    = typeof minY != 'undefined' ? minY : null;
        o.maxX    = typeof maxX != 'undefined' ? maxX : null;
        o.maxY    = typeof maxY != 'undefined' ? maxY : null;

        o.xMapper = fXMapper ? fXMapper : null;
        o.yMapper = fYMapper ? fYMapper : null;

        id = o.id.replace('xajax_im_head_','');
        var pagestart = readCookie('chatperso'+id+'start');
        //new fenster
        var openwdw = readCookie('chatperso'+id+'open');
        if( (!isNaN(parseInt(openwdw))) &&  parseInt(openwdw) > 0 ){
        	createCookie( 'chatperso'+id+'open', '0',1);
        	eraseCookie('chatperso'+id+'open');
        	checkrwopen(id);
        	updateCookies( id, startw, starth, id );
        	o.root.style.left   = startw+"pt";
        	o.root.style.top   = starth+"pt";
        	openwdw = true;
        } else {
        	openwdw = false;
        }

        //re-place fenster (page load)
        if( !pagestart || isNaN(parseInt(pagestart)) ||  parseInt(pagestart) < 1 ){
 //
        	eraseCookie('chatperso'+id+'start');
        	createCookie('chatperso'+id+'start', 1, 1);
        	
        	w = readCookie('chatperso'+id+'w');
        	if( !w || w < startw+50 ){
        		//w = (window.screen.width/2) - rand_min(180);
        		w = rand_min(startw+50);
        		//w = 400;
        	}
//
        	if( w && openwdw==false ){
        		if( w > 1000 ) {
        			w = w-200;
        		}
        		o.root.style.left   = w+"pt";
        	}       	
        	h = readCookie('chatperso'+id+'h');
        	if( !h || h < 160 ){
        		h = rand_min(160);
        	}
        	if( h  && openwdw==false  ){
        		o.root.style.top   = h+"pt";
        	}
	
        	id = readCookie('chatpersoid');
			if( o.id == id ){
				o.root.style.zIndex = 910;
			}
        }

        o.root.onDragStart    = new Function();
        o.root.onDragEnd    = new Function();
        o.root.onDrag        = new Function();
    },

    start : function(e)
    {
//alert(" 2 ");
        var o = Drag.obj = this;
        e = Drag.fixE(e);
        var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
        o.root.onDragStart(x, y);

        o.lastMouseX    = e.clientX;
        o.lastMouseY    = e.clientY;

        if (o.hmode) {
            if (o.minX != null)    o.minMouseX    = e.clientX - x + o.minX;
            if (o.maxX != null)    o.maxMouseX    = o.minMouseX + o.maxX - o.minX;
        } else {
            if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
            if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
        }

        if (o.vmode) {
            if (o.minY != null)    o.minMouseY    = e.clientY - y + o.minY;
            if (o.maxY != null)    o.maxMouseY    = o.minMouseY + o.maxY - o.minY;
        } else {
            if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
            if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
        }

        document.onmousemove    = Drag.drag;
        document.onmouseup        = Drag.end;
        
        

        return false;
    },

    drag : function(e)
    {
        e = Drag.fixE(e);
        var o = Drag.obj;

        var ey    = e.clientY;
        var ex    = e.clientX;
        var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
        var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
        var nx, ny;

        if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
        if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
        if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
        if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

        nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
        ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

        if (o.xMapper)        nx = o.xMapper(y)
        else if (o.yMapper)    ny = o.yMapper(x)

        Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
        Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
        Drag.obj.lastMouseX    = ex;
        Drag.obj.lastMouseY    = ey;
//
        Drag.lastx = nx;
        Drag.lasty = ny;
//
        Drag.obj.root.onDrag(nx, ny);
        return false;
    },

    end : function()
    {
        document.onmousemove = null;
        document.onmouseup   = null;
        Drag.obj.root.onDragEnd(    parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
                                    parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
//
//
        var myid = Drag.obj.id.replace('xajax_im_head_','');
//alert( Drag.lastx + ', ' + Drag.lasty + ', ' + myid  );
		var w = Drag.lastx + rand_delta( ) - 180;
		var h = Drag.lasty + rand_delta( ) + 40;
		var ids;
		
		for(n in opens){
			var n_int = parseInt(n);
			if( isNaN( n_int ) ) continue;
			if( !n_int ) continue;
			if( n_int < 1 ) continue;
			checkrwopen( n_int );
			if( n_int == myid ) continue;
		//

		// re-place unused fenster in background
			/*
			if( document.getElementById('xajax_im_open_' + n_int) ){
				document.getElementById('xajax_im_open_' + n_int).style.left = w+'pt';
				document.getElementById('xajax_im_open_' + n_int).style.top = h+'pt';
				//document.getElementById('xajax_im_open_' + n_int).style.zIndex = 900;
				w += 30;
				h += 20;
				updateCookies( n_int, w, h );
			}
			*/
		}
//
		updateCookies( myid, Drag.lastx, Drag.lasty, myid );
		//document.getElementById('xajax_im_open_' + myid).style.zIndex = 910+opens.lenth;

        Drag.obj = null;
    },

    fixE : function(e)
    {
        if (typeof e == 'undefined') e = window.event;
        if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
        if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
        return e;
    }
};

//
function doOpen(id) {
	createCookie( 'chatperso'+id+'open','2',1);
}
function closeOpen(id) {
	var myid = 'chatperso'+id
	document.getElementById('xajax_im_open_' + id).style.visibility = "hidden";
	eraseCookie(myid+'w');
	eraseCookie(myid+'h');
}
