/* dragNdrop 
 o part of gareus.org website
 * (c) 2005, 2006 robin@gareus.org
 * use in terms of the GPL
 */

//window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

var icon = new Array(), zIndex = new Array() , dragged_item, current_caption, current_popup, t_click;
var trash = new Array();


////////////////////////////////
// general JS
function show(foo) {
    document.getElementById(foo).style.display="block";
}

function hide(foo) {
    document.getElementById(foo).style.display="none";
}

function updateText (elem,val) {
  var Textknoten = document.createTextNode(val);
  document.getElementById(elem).replaceChild(Textknoten, document.getElementById(elem).firstChild);
}


var win_x, win_y; // browser window size

function getWindowSize() { 
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    win_x = window.innerWidth;
    win_y = window.innerHeight;
  } else if( document.documentElement &&
           ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    win_x = document.documentElement.clientWidth;
    win_y = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    win_x = document.body.clientWidth;
    win_y = document.body.clientHeight;
  }
}
//
////////////////////////////////

function resizeItemFrame() {
/*
  var max_x,max_y;
  max_x=win_x-30;
  max_y=win_y-30;
  if (max_x <100 || max_y < 100) return;

  for (var i=0; i<icon.length; i++) {
    var ix = parseInt(icon[i].style.left);
    var iy = parseInt(icon[i].style.top);
    if (ix >= max_x ) { icon[i].style.left = max_x+'px';}
    if (iy >= max_y ) { icon[i].style.top = max_y+'px'; }
  }
*/
}

function so_init()
{
  dragged_item = new Number(0); // number of icon that is dragged
  current_caption=""; // temp. hack -> TODO: get from dragged_item
  current_popup=-1;

  getWindowSize();
  window.onresize = function () {getWindowSize(); resizeItemFrame();} 


  var now = new Date();
  t_click = now.getTime(); // initialize click time

  document.onmousemove = mouseMove; // enable/capture mouseMove event
  document.onmouseup = mouseUp; // document wide stop dragging when mouseUp

 //   document.getElementById('maintable').onmousemove = mouseMove; // enable/capture mouseMove event
 //   document.getElementById('maintable').onmouseup = mouseUp; // document wide stop dragging when mouseUp
}


////////////////////////////////
// Popup Div
var perc=90;

function shrink() {
   if (perc > 30) {perc=perc-10;}
   document.getElementById('popup').style.width=perc+'%';
   document.getElementById('popup').style.left=((100-perc)/2)+'%';
}
function expand() {
   if (perc < 100) {perc=perc+10;}
   document.getElementById('popup').style.width=perc+'%';
   document.getElementById('popup').style.left=((100-perc)/2)+'%';
}
function normal() {
   perc=70;
   document.getElementById('popup').style.width='70%';
   document.getElementById('popup').style.left='15%';
}
function maximize() {
   perc=100;
   document.getElementById('popup').style.width='100%';
   document.getElementById('popup').style.left='0px';
}
// End Popup Div
////////////////////////////////


function mouseOver(e) {
  if (!e) var e = event;
  if (this.type==2) { document.getElementById(this.name+"_img").src=this.swapsrc; fixPNG(document.getElementById(this.name+"_img"),this.name); }
  var x = parseInt(this.style.left) - 3;
  var y = parseInt(this.style.top) - 2;
  this.style.left = x + "px";
  this.style.top = y + "px";
}


function mouseOut(e) {
  if (!e) var e = event;
  if (this.type==2) { document.getElementById(this.name+"_img").src=this.realsrc; fixPNG(document.getElementById(this.name+"_img"),this.name); }
  var x = parseInt(this.style.left) + 3;
  var y = parseInt(this.style.top) + 2;
  this.style.left = x + "px";
  this.style.top = y + "px";
}

////////////////////////////////
// Click on Image
function imgmouseUp() {
	if (this.dragging) {
		var click_speed = 200; // click speed in ms
		var now = new Date();
		var t_drop = now.getTime();
		if (t_drop - t_click < click_speed) {
		   if (this.id=="item14") {
		   	undo_trash();
		   } else {
			setpopup(dragged_item);show('popup');
		   }
		}
    		if (this.type==1) document.getElementById(this.name+"_img").src=this.realsrc;
	}
}

function setpopup(itemno) {
  if (current_popup != itemno) {
    current_popup= itemno;
    if (itemno<0) {
	document.getElementById('popupFrame').src='popup.htm';
    	return;
    } 
    document.getElementById('popupFrame').src=icon[itemno].link;
  }
}

function mouseUp() {
	var i =parseInt(dragged_item);
	icon[i].dragging = false; 
	if (current_caption != "") hide(current_caption);
    	if (icon[i].type==1) document.getElementById(icon[i].name+"_img").src=icon[i].realsrc;
}
// END - Click on Image
////////////////////////////////

////////////////////////////////
// Drag N Drop

// Read in image into icon-array
function init_item(icon_name,popup_url,type,swap,offset_x,offset_y,overlap_x,overlap_y)
{	
  var i = icon.length; // first free entry in icon array
  icon[i] = document.getElementById(icon_name);
  icon[i].name = icon_name;
  icon[i].link = popup_url;
  icon[i].realsrc = document.getElementById(icon_name+"_img").src;
  icon[i].swapsrc = swap;
  icon[i].type = type;
  icon[i].offset_y = offset_y;
  icon[i].offset_x = offset_x;
  icon[i].overlap_x = overlap_x;
  icon[i].overlap_y = overlap_y;

  fixPNG(document.getElementById(icon_name+"_img"),icon_name);

  icon[i].idx = i; // icon index/number
  var x = parseInt(icon[i].style.left);
  var y = parseInt(icon[i].style.top);
  icon[i].style.left = x + "px";
  icon[i].style.top = y + "px";
  icon[i].dragging = false;
  icon[i].onmousedown = mouseDown;
  icon[i].onmouseup = imgmouseUp;

  icon[i].onmouseover = mouseOver;
  icon[i].onmouseout = mouseOut;

  icon[i].status = 1;
  zIndex[icon[i].style.zIndex] = i; // put icon number in zIndex LUT
  return true;
}

// Mouse down event handler
function mouseDown(e)
{
  if (!e) var e = event; // explicitly get event if not already given (some browsers need this)
  if (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) return false; // don't start moving if modifier keys pressed

  var now = new Date();
  t_click = now.getTime(); // store click time
  if (!this.dragging)
  {
    current_caption=this.name+"_caption";
    show(current_caption);

    this.dragging = true;
    this.dx = e.clientX - parseInt(this.style.left);
    this.dy = e.clientY - parseInt(this.style.top);
    dragged_item = this.idx;
    putOnTop(Number(dragged_item)); 
    if (this.type==1) { 
	document.getElementById(this.name+"_img").src=this.swapsrc;
    }
  }
  else
    this.dragging = false; // just to be sure: prevent sticky icons
  return false;
}

function putOnTop(i) {
    if (icon[i].style.zIndex != icon.length - 1) // icon not already on top
    {
      var z = new Number(icon[i].style.zIndex);
      for (var j=z+1; j<icon.length; j++) // move icons above current down wrt. zIndex
      {
        icon[zIndex[j]].style.zIndex = icon[zIndex[j]].style.zIndex - 1;
        zIndex[j-1] = zIndex[j];
      }
      icon[i].style.zIndex = icon.length - 1; // current icon on top
      zIndex[icon.length - 1] = i; // also in zIndex LUT
    }
}

var score=1000;
var magcnt=0;
var clkcnt=0;
var eventA=0;
var eventB=0;
var eventC=0;
var eventD=0;
var eventE=0;
var eventF=0;
var eventG=9;

// Mouse move event handler
function mouseMove(e)
{
  if (!e) var e = event;
  var i = new Number(dragged_item); // convert from string to integer

  if (e.clientX < 5 || e.clientY < 5 || Math.abs(win_x - e.clientX) < 5 || Math.abs(win_y - e.clientY) < 5 ) {mouseUp();} // stop drag when mouse hits window boundary.
 
  if (icon[i].dragging && (icon[i].status & 1))
  {
    putOnTop(i);
    var x = e.clientX - icon[i].dx;
    var y = e.clientY - icon[i].dy;
    icon[i].style.left = x + "px";
    icon[i].style.top = y + "px";

    // special Events
   
    if (i==2) make_batt();
   
    if (gameevent(i,13,4) && eventC>0) make_magnet(parseInt(icon[4].style.left),parseInt(icon[4].style.top));
    if (gameevent(i,3,7)) { make_info();}
    if (i==3 && gameevent(i,3,2)) { make_time();}

    if (eventC==0 && eventD==0 && i==6 && gameevent(i,6,2)) { eventD=1; make_wrongboard();}
    else if (eventC==1 && i==6 && gameevent(i,6,2)) { eventC=2; clkcnt=0; make_swallowknight();}
   
    //if (eventB==1 && i!=7 && i!=3 && i!=5 && gameevent(i,i,7)) { make_girls();}
    if (eventB==1 && i!=7 && gameevent(i,8,7)) { make_girls();}
    else if (eventB==0 && eventE==0 && (i==8 || i==4 || i==13 || i==9 || i==10 || i==11) && gameevent(i,i,7)) { eventE=1; make_nogirls();}
    else if (eventB==1 && eventE<2 && (i==8 || i==4 || i==13 || i==9 || i==10 || i==11) && gameevent(i,i,7)) { eventE=2; make_ungirls();}
  
    if (i!=14 && gameevent(i,i,14)) { make_trash(i);}
    if (gameevent(i,5,7) && magcnt > 15) { make_bzzz(); eventA=1; if(eventB==0) eventB=1; }
    else if (eventA==1) { infopopdown(); eventA=0;}

    if (eventF>1 && gameevent(i,15,9) && gameevent(i,15,10) && gameevent(i,15,11)) { make_light();}
    else if (eventF<3 && gameevent(i,9,10) && gameevent(i,9,11)) { make_bright();}

  }
  return false;
}

function gameevent(i,n,m) {
  if ( !(icon[n].status&1) || !(icon[m].status&1) ) { return(false);}

  if ( (i==n && icon[n].dragging) || (i==m && icon[m].dragging) )  {
    if (
    	Math.abs(parseInt(icon[n].style.left)+parseInt(icon[n].offset_x)-parseInt(icon[m].style.left)-parseInt(icon[m].offset_x)) < (parseInt(icon[n].overlap_x)+parseInt(icon[m].overlap_x)) && 
    	Math.abs(parseInt(icon[n].style.top)+parseInt(icon[n].offset_y)-parseInt(icon[m].style.top)-parseInt(icon[m].offset_y)) < (parseInt(icon[n].overlap_y)+parseInt(icon[m].overlap_y))
	) return(true);
  }
  return(false);
}

function make_magnet(x,y) {	
	{
	  magcnt=magcnt+1;
	  if (magcnt==15)  {
		score=score+2000; updateText('Score','Score: '+score);
		show('item5');
		document.getElementById('item5').style.left = x + "px";
		document.getElementById('item5').style.top = y + "px";
	  }
	  if (magcnt%120==0)  {
		score=score+50; updateText('Score','Score: '+score);
	  	show('scorepopup');
		setTimeout(scorepopdown,800);
	  }
	  if (magcnt==2)  {
		score=score+10; updateText('Score','Score: '+score);
	  	updateText('infotext','OOps. something happened. keep moving things around.');
	  	show('infopopup');
		setTimeout(infopopdown,3000);
	  }
	}
}

function make_swallowknight() {	
	hide('item6');
	document.getElementById('item6').style.left = "-100px";
	document.getElementById('item6').style.top = "-100px";
	updateText('infotext','You place the Knight on the board, where the battery was hidden.');
	score=score+25; updateText('Score','Score: '+score);
	show('infopopup');
}

function make_batt() {	
	if (eventC==0)  {
		show('item13');
	  	updateText('infotext','There was a battery hidden on the board.');
	 	score=score+550; updateText('Score','Score: '+score);
	  	show('infopopup');
		eventC=1;
	}
	if (eventC==2)  {
		var x = parseInt(icon[2].style.left) + 24;
		var y = parseInt(icon[2].style.top) +24;
		show('item6');
		eventC=1;
		document.getElementById('item6').style.left = x + "px";
		document.getElementById('item6').style.top = y + "px";
	  	updateText('infotext','As you move the board, the Chess piece falls off again..');
	  	show('infopopup');
		clkcnt=0;
	}
}

function undo_trash() {
	// pop item from trash.
	if (trash.length == 0) {
	  	updateText('infotext','There is nothing inside the bin.');
	  	show('infopopup');
	}
  	var last = trash.length-1; 
	var i= trash[last];
	show('item'+i);
  	icon[i].status = 1;
	trash.length--;
	score=score+5; updateText('Score','Score: '+score);
}

var trashsound= new Array("klonk!","swush!","whizz!","Bang."); 

function make_trash(i) {
  	var next = trash.length; 
	hide('item'+i);
  	icon[i].status = 0;
        icon[i].dragging = false; // just to be sure: prevent sticky icons
    	if (icon[i].type==1) document.getElementById(icon[i].name+"_img").src=icon[i].realsrc;
	trash[next]=i;
	updateText('infotext',trashsound[((i+next)%(trashsound.length))]);
	show('infopopup');
	if (i==7 && eventB==1) { eventB=0; eventE=0; }
	if (trash.length > eventG) {
	   eventG=trash.length;
	   var bonus = 60 * eventG * eventG;
	   score=score+bonus; updateText('Score','Score: '+score);
	   updateText('infotext','Nice cleaning job: '+eventG+' items -> '+bonus+' points.');
	} else {
	  setTimeout(infopopdown,800);
	}
}

function make_girls() {	
  	var x = parseInt(icon[7].style.left) + 24;
  	var y = parseInt(icon[7].style.top) +83;
	if (eventB!=2)  {
		show('item12');
		eventB=2;
		document.getElementById('item12').style.left = x + "px";
		document.getElementById('item12').style.top = y + "px";
		score=score+10000; updateText('Score','Score: '+score);
	  	updateText('infotext','You install open-source software on the TV. It works now!');
	  	show('infopopup');
	}
}

function make_ungirls() {	
	 updateText('infotext','The TV does not boot..');
	 score=score+1000; updateText('Score','Score: '+score);
	 show('infopopup');
}

function make_nogirls() {	
	 updateText('infotext','The TV seems to be stuck.');
	 show('infopopup');
}

function make_wrongboard() {	
	 updateText('infotext','The Chess Piece does not fit on the Strageo Board.');
	 show('infopopup');
}

function make_info() {	
         if (score > 0) score=score-1; updateText('Score','Score: '+score);
	 updateText('infotext','Move the clock away from the TV Screen please - it does not belong there! Then close this dialog. Thanks.');
	 show('infopopup');
}

function make_bright() {	
	 updateText('infotext','Those LED colours would probably add up to white.');
	 show('infopopup');
}

function make_light() {	
	 if (eventF==2) {
	   score=score+20000; updateText('Score','Score: '+score);
	   updateText('infotext','Wow, a LED lighthouse! You are awarded 20000 bonus points.');
	   eventF=3;
	   show('scorepopup');
	   setTimeout(scorepopdown,800);
	 } else {
	   updateText('infotext','You just build a lighthouse.');
	 }
	 show('infopopup');
}

function make_time() {	
	 if (eventF>1) { return; }
         clkcnt++;

	 if (clkcnt>200 && eventF==1 && eventC==2) {
	   updateText('infotext','mmh, this is really a tricky situation.');
	   show('infopopup');
	   clkcnt=0;
	 } else if (clkcnt> 150 && eventF==1 && eventC==1) {
	   updateText('infotext','got it! you have captured the enemy flag tower.');
	   eventF=2;
	   score=score+7000; updateText('Score','Score: '+score);
	   show('infopopup');
	   // TODO show flag ;)
	   show('item15');
	   var x = parseInt(icon[2].style.left) +125;
	   var y = parseInt(icon[2].style.top)  -75;
	   document.getElementById('item15').style.left = x + "px";
	   document.getElementById('item15').style.top = y + "px";
	 } else if (clkcnt> 100 && eventF==0 && eventC==2) {
	   updateText('infotext','You think you found a move. - oh wait no, that one is a chess piece.. hang on.');
	   show('infopopup');
	   score=score+1000; updateText('Score','Score: '+score);
	   eventF=1;
	   clkcnt=0;
	 } else if (clkcnt>15) {
	   updateText('infotext','You ponder about Chess and Stratego - Time flies..');
	   show('infopopup');
	   if (clkcnt>150) { clkcnt==0;}
	 }
}

function make_bzzz() {	
	 updateText('infotext','Bzzzz.');
	 show('infopopup');
}

function scorepopdown() { hide('scorepopup'); }

function infopopdown() { hide('infopopup'); }

