
function removeAllChildren(element){
	if(element==null){
		return;
	}
	child=element.firstChild;
	while(child!=null){
		element.removeChild(child);
		child=element.firstChild;
	}
}


function createRequestObject() {
  var anfrage = null;
  try {
    anfrage = new XMLHttpRequest();
  } catch (versuchmicrosoft) {
    try {
      anfrage = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (anderesmicrosoft) {
      try {
	anfrage = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (fehlschlag) {
	anfrage = null;
      }
    }
  }
  
  if (anfrage == null)
    alert("Fehler beim Erzeugen des Anfrage-Objekts!");
  return anfrage;
}
// function createRequestObject() {
//     var ro;
//     var browser = navigator.appName;
//     if(browser == "Microsoft Internet Explorer"){
//         ro = new wwActiveXObject("Microsoft.XMLHTTP");
//     }else{
//         ro = new XMLHttpRequest();
//     }
//     return ro;
// }




function UpdateBoard() {

    var sessionid = getValue('sessionid');

    var url = escape('board.xml')+'?sessionid='+sessionid;

    requestBoardData(url);
    setTimeout("UpdateBoard()",2000);
}


function preloadImage(container,id)
{
  var pfad = getValue('carddeck');
  var ext  = getValue('cardext');
  var cw  = getValue('cardwidth');
  var ch  = getValue('cardheight');

  var img          =  new Image();
  img.src          =  pfad+'/'+id+'.'+ext;
  img.id           = pfad+'/'+id;
  
  //img.nodeClass        = 'none';

  var oattr        = document.createAttribute('class');
  oattr.value      = 'none';    
  img.setAttributeNode(oattr);   

  img.style.width  = cw+"px";
  img.style.height = ch+"px";
  img.onclick      = clickCard;
  container.appendChild(img);
}

function preloadImage2(container,id,src)
{
  var img          =  new Image();
  img.src          =  src;
  img.id           =  id;
  

  var oattr        = document.createAttribute('class');
  oattr.value      = 'none';    
  img.setAttributeNode(oattr);   

  img.style.width  = "20px";
  img.style.height = "20px";

  container.appendChild(img);
}


function loadImages() {
  //preloading images

  try
    {
      var container = document.getElementById("container"); 
      //container.style.display = "none;"; //Exception in IE
      for(var x = 1; x < 37 ; x++) {
	preloadImage(container,x);
	preloadImage(container,x);
      }
      for(var y = 0; y < 14 ; y ++)
	{
	  preloadImage(container,0);
	}
      for(var z = 0; z < 4 ; z ++)
	{
	  preloadImage2(container,"active0","active0.jpg");
	  preloadImage2(container,"active1","active1.jpg");
	  preloadImage2(container,"duplicate0","duplicate0.jpg");
	  preloadImage2(container,"duplicate1","duplicate1.jpg");
	  preloadImage2(container,"give0","give0.jpg");
	  preloadImage2(container,"give1","give1.jpg");
	}
      
    }
  catch(exc)
    {
      log_error("preloadImages "+exc);
    }
}
function clickCard()
{
 var div = this.parentNode;
 var id = div.id;
 
 if(id != container)
   selectCard(id);
 return;
}

      

//name="card1" onclick="selectCard('card1')"

function getValue(id)
{
	var span = document.getElementsByTagName("span");
	for(var x=0;x<span.length;x++) {
		if (span[x].className == id) {
                        return span[x].id;
                }    
        }          
        return null;
}  

function requestBoardData(url){
	var request=createRequestObject();

	url = url + "&dummy=" + new Date().getTime();

	request.open('get', url ,true);
	request.onreadystatechange = function () {handleState(request)};
	request.send(null);
}

function replaceText(text,s,e)
{
  while(true)
    {
      var pos = text.indexOf(s);
      if(pos < 0) break;
      text = text.substring(0,pos) + e + text.substring(pos + s.length);
    }
  return text;
}

function replaceSZ(text)
{
  //replace ie &uuml; => ü
  text = replaceText(text,"&uuml;","\u00fc");
  text = replaceText(text,"&ouml;","\u00f6");
  text = replaceText(text,"&auml;","\u00e4");
  text = replaceText(text,"&Uuml;","\u00dc");
  text = replaceText(text,"&Ouml;","\u00d6");
  text = replaceText(text,"&Auml;","\u00c4");
  text = replaceText(text,"&szlig;","\u00df");
  return text;
}

function boardSetText(spanid,text)
{ 
 
  text = replaceSZ(text);
  var span = document.getElementById(spanid);
  removeAllChildren(span);
  
  span.className = "snippetLoaded";
  
  // replace "<b>" text by <strong> node
  var pos1=text.indexOf("<b>");
  var pos2=text.indexOf("</b>");
  while (pos1 >= 0 && pos2 > pos1) {
    leftString = document.createTextNode(replaceSZ(text.substring(0, pos1))); //other text
    if (leftString != "") span.appendChild(leftString);
    
    //add the bold text
    strongNode=document.createElement("strong");
    middleString=document.createTextNode(replaceSZ(text.substring(pos1 + 3, pos2)));
    strongNode.appendChild(middleString);
    span.appendChild(strongNode);
    
    // cut out left and middle and go on with remaining text
    text=text.substring(pos2 + 4);
    pos1=text.indexOf("<b>");
    pos2=text.indexOf("</b>");
  }
  
  // add remaining string
  //if (text != "") {
  span.appendChild(document.createTextNode(text));
  //}
  
}

function handleState(req) {
        if(req.readyState != 4){
		return;
	}
	var response = req.responseXML;

	try
	  {
	    var err = response.getElementsByTagName("error")[0].firstChild.data;

	    //log("request with error:"+err);
		
	    if(err != 0)
	      {
		var rep = response.getElementsByTagName("replace")[0].firstChild.data;
		var sessionid = getValue('sessionid');
		location.replace(rep+'?sessionid='+sessionid,'SpielGeist');
	      }
	  }
	catch(exc1)
	  {
	    log_error("err:"+err+" "+exc1.message);
	  }
	try
	  {
	    var commando = response.getElementsByTagName("text")[0].firstChild.data;
	    boardSetText("command",commando);
	  }
	catch(exc2)
	  {
	    log_error("commando:"+exc2.message);
	  }
	try
	  {
	    var info = response.getElementsByTagName("info")[0].firstChild.data;
	    boardSetText("info",info);
	    
	    for(var x = 0;x < 4;x++) {       
	      var ans = response.getElementsByTagName('answer'+x)[0].firstChild.data;
	      boardSetText('answer'+x,ans);
	    }
	  }
	catch(exc)
	  {
	    log_error("info and answers "+exc.message);
	  }
	try
	  {
	    //my cards      
            var pfad = getValue('carddeck');
            var ext  = getValue('cardext');
	    var cardanz  = response.getElementsByTagName('cardanz')[0].firstChild.data;
	    for(var x = 0;x < cardanz;x++) {       
	      var imagenr    = response.getElementsByTagName('card'+x)[0].firstChild.data;
	      setImage('card'+x,pfad+'/',imagenr,ext);
	    }


	    //deck 
	    var deskanz  = response.getElementsByTagName('deskanz')[0].firstChild.data;
	    
	    for(var x = 0;x < deskanz;x++) {       
	      var imagenr    = response.getElementsByTagName('desk'+x)[0].firstChild.data;
	      setImage('desk'+x,pfad+'/',imagenr,ext);
	    }
	  }
	catch(exc3)
	  {
	    log_error("cards "+exc3.message);
	  }
	
	//player
	for(var x = 0;x < deskanz;x++) {
	  try
	    {
	      //Name of Player
	      var o    =  response.getElementsByTagName('pname'+x)[0].firstChild;
	      if(o == null) continue;
	      
	      var name =  response.getElementsByTagName('pname'+x)[0].firstChild.data;
	      boardSetText('name'+x,name);
	      var punkte =  response.getElementsByTagName('punkte'+x)[0].firstChild.data;
	      boardSetText('punkte'+x,punkte);
	      var power =  response.getElementsByTagName('power'+x)[0].firstChild.data;
	      boardSetText('power'+x,power);
	    }
	  catch(exc5)
	    {
	      log_error("part1 "+exc5.message+" index:"+x);
	    }


	  try
	    {
	      var imagenr    = response.getElementsByTagName('duplicate'+x)[0].firstChild.data;
	      setImage('divduplicate'+x,'duplicate',imagenr,'jpg');

	      var actnr    = response.getElementsByTagName('active'+x)[0].firstChild.data;
	      setImage('divactive'+x,'active',actnr,'jpg');

	      var givenr    = response.getElementsByTagName('give'+x)[0].firstChild.data;
	      setImage('divgive'+x,'give',givenr,'jpg');
	    }
	  catch(exc4)
	    {
	      log_error("part2"+exc4.message+" index:"+x);
	    }
	  
	  try
	    {
	      var valuationimage  = response.getElementsByTagName('valuation')[0].firstChild.data;
	      if(oldvaluationimage == null || oldvaluationimage < valuationimage || oldvaluationimage > valuationimage)
		{
		  var sessionid = getValue('sessionid');
		  var opt = '?sessionid='+escape(sessionid)+'&dummy='+new Date().getTime();
		  //setImage2('divvaluation',valuationimage+opt+"&width=50&height=40",50,40);
		  setImage2('divbigvaluation',valuationimage+opt+"&width=500&height=400",500,400);
		}
	      oldvaluationimage = valuationimage;
	    }
	  catch(exc5)
	    {
	      log_error("valuation"+exc5.message);
	    }
	}
	//span.removeChild(span.firstChild);
}


function getImage(div,id)
{
  for(var x = 0;x < div.childNodes.length;x++)
    {
      var e = div.childNodes[x];
      if(e.nodeName == 'IMG')
	{
	  if(id == null || e.id == id)
	    return e;
	}
    }
  return null;
}

function setImage(tag,name,nr,ext) 
{
  var cdiv = document.getElementById(tag);
  if(cdiv != null && cdiv.nodeName == 'DIV')
    {
      var container = document.getElementById("container"); 
      //AltNeu vergleich
      var img = getImage(cdiv,null); 
      if(img != null)
	{
	  if(img.id == name+nr) //alles Ok
	    return null;
	  //move image to container 
	  container.appendChild(img); //It automaticcly remove it from cdiv
      	}
      var nimg = getImage(container,name+nr);
      if(nimg != null)
	cdiv.appendChild(nimg);
    }
  else
    {
      //Alte Methode
      var source = name+nr+'.'+ext;
      //if(document[tag].src != source)
      document[tag].src = source;
    }
}
function setImage2(tag,name,width,height) 
{
  var cdiv = document.getElementById(tag);    
  var img          =  new Image();
  img.src          =  name;
  img.id           =  tag+'id';

  var oattr        = document.createAttribute('class');
  oattr.value      = 'none';    
  img.setAttributeNode(oattr);   

  img.style.width  =  width +"px";
  img.style.height =  height +"px";
  removeAllChildren(cdiv);
  cdiv.appendChild(img);
}
function selectCard(card)
{
   var sessionid = getValue('sessionid');

   var url = escape('board.xml')+'?sessionid='+escape(sessionid)+'&action='+escape(card);
   requestBoardData(url);

   //boardSetText("command",url);

}

function checkform(id)
{
  var o = document.getElementById(id);
  //alert(o.value);
}

var oldvaluationimage = null;

function BoneheadId() {
  var Wert = "";
  if (document.cookie) {
    var Wertstart = document.cookie.indexOf("=") + 1;
    var Wertende = document.cookie.indexOf(";");
    if (Wertende == -1)
      Wertende = document.cookie.length;
    Wert = document.cookie.substring(Wertstart, Wertende);
  }
  return Wert;
}

function WertSetzen (Bezeichner, Wert) {
  var Verfall = 1000 * 60 * 60 * 24 * 365;
  var jetzt = new Date();
  var Auszeit = new Date(jetzt.getTime() + Verfall);
  document.cookie = Bezeichner + "=" + Wert + "; expires=" + Auszeit.toGMTString() + ";";
}

function log_error(exception)
{
  var sessionid = getValue('sessionid');
  var url = escape('error.xml')+'?sessionid='+escape(sessionid)
    +'&exception='+escape(exception)+'&dummy='+new Date().getTime();

  var request=createRequestObject();
  
  if(request == null) return;
  request.open('get', url ,true);
  //request.onreadystatechange = function () {handleState(request)};
  request.send(null);
}

function log(mesg)
{
  var sessionid = getValue('sessionid');
  var url = escape('logging.xml')+'?sessionid='+escape(sessionid)
    +'&message='+escape(mesg)+'&dummy='+new Date().getTime();

  var request = createRequestObject();
  
  if(request == null) return;
  request.open('get', url ,true);
  //request.onreadystatechange = function () {handleState(request)};
  request.send(null);
}





//snapshot
var state = 0;

function closesnap()
{
 state = 0;
 setTimeout('fsm()',100);
}

function opensnap()
{
 state = 1;
 setTimeout('fsm()',100);
}
function fsm()
{
var a = getPageSize()

var div1     =  document.getElementById('overlay1');      
var div2     =  document.getElementById('overlay2');      
var div3     =  document.getElementById('overlay3');      
var img1     =  document.getElementById('overlayimage1');      
var img2     =  document.getElementById('divbigvaluationid');      
var img3     =  document.getElementById('overlayimage3');      
 
switch(state)
{
case 0:
  div1.style.display = "none";
  div2.style.display = "none";
  div3.style.display = "none";
  break;
case 11:
  break;
default:
  var ih = 400 * state/10;
  var iw = 500 * state/10;
  var xtop = 80;
  var tw = a[0] * 0.9;
  var th = a[1] * 0.8;

  div1.style.top  = "10px";
  div1.style.left = ((a[0] - tw)/2) +"px";

  div2.style.top  = xtop +"px";
  div2.style.left = ((a[0] - iw)/2) +"px";
  div3.style.top  = xtop + 1 + "px";
  div3.style.left = ((a[0] - iw )/2 + iw - 20 + 1) +"px";
 
  img1.style.width = tw+"px";
  img1.style.height = th+"px";
  if(img2)
    {
      img2.style.width = iw+"px";
      img2.style.height = ih+"px";
    }
  img3.style.width = "20px";
  img3.style.height = "20px";
  
  div1.style.display = "block";
  div2.style.display = "block";
  div3.style.display = "block";

  state++;
  setTimeout('fsm()',10);
  break;
}

}
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
