/* ---- LaserGame 1.0: engine hry ----- */
/* (c) zby.cz '05 (zbytovsky gmail.com) */
/* ------------------------------------ */

//$date: 05/04/23; $rows: 549;


function geto(id){
return document.getElementById(id);
}/*základní funkce vracející objekt*/


var ctverec=14;
var imgpath="data/grafika/";
var levpath="data/lev/";
/*konstanty*/


var zrcadla=new Array();
zrcadla["1|0;-1"]=[-1,0];
zrcadla["1|1;0"]=[0,1];
zrcadla["2|0;1"]=[-1,0];
zrcadla["2|1;0"]=[0,-1];
zrcadla["3|0;1"]=[1,0];
zrcadla["3|-1;0"]=[0,-1];
zrcadla["4|0;-1"]=[1,0];
zrcadla["4|-1;0"]=[0,1];

zrcadla["5|0;-1"]=[0,1];
zrcadla["6|1;0"]=[-1,0];
zrcadla["7|0;1"]=[0,-1];
zrcadla["8|-1;0"]=[1,0];
/*pole obsahující odraz zrcadel*/


var laser; //umístění Array(x,y,typ);
var smer; //pole [x,y];
var int1; //interval pro laser
var user_zrcad=new Array(); //proměnná pro daočasná zrcadla
var level_mapa=new Array(); //proměnná pro dočasné zdi
var level=new Array(); level["info"]=new Array();
/*globální proměnné*/


var cislo_levelu=parseInt(get_user().split(";")[0]);
if(tmp=window.location.hash.substr(1)) cislo_levelu = tmp;
window.setInterval('tmp=window.location.hash.substr(1);if(tmp&&tmp!=cislo_levelu)location.reload(true);', 1000);
if(cislo_levelu) document.write("<script type=\"text/javascript\" src=\""+levpath+"lev"+cislo_levelu+".js\"></script>\n");
/*vložení includu levelu*/


function vytvor_laser(){
  laser=false;
  smer=false;
  if(geto("laser")) geto("laser").parentNode.removeChild(geto("laser"));
  /*obnovovací opatření*/
    
  var arr=level["info"]["start"];
  var x=arr[0];
  var y=arr[1];
  
  var typ;
  if(arr[2]==1){
    typ=2;
    smer=[0,1];
    y++;
  }
  if(arr[2]==2){
    typ=1;
    smer=[-1,0];
  }
  if(arr[2]==3){
    typ=2;
    smer=[0,-1];
  }
  if(arr[2]==4){
    typ=1;
    smer=[1,0];
    x++;
  }
  /* vytvoření prvotního směru a typu na startu*/
  
  x=x+smer[0];
  y=y+smer[1];
  laser=new Array(x,y,typ);
  /*aktualni pozice laseru */
  
  var x_px=(x*ctverec)-1;
  var y_px=(y*ctverec)-1;
  /*výpočet pixelů*/

  if(smer[0]==1){
    x_px-=ctverec;
  }
  if(smer[1]==1){
    y_px-=ctverec;
  }
  /*korekce posunutí*/
  
  newImg=document.createElement("img");
  newImg.setAttribute("id","laser");
  newImg.setAttribute("name","laser");
  newImg.style.left=x_px;
  newImg.style.top=y_px;
  newImg.typ=typ;
  geto("mapa").appendChild(newImg);
  /*nastavení vlastností nového objektu*/
  geto("laser").src=imgpath+barvalaseru+typ+".gif"; 
  /*abychom mohli obnovovat, nastavíme přímo*/
}


function posun_laser(){
  var x=laser[0];
  var y=laser[1];
  
  if(x==level["info"]["cil"][0] && y==level["info"]["cil"][1]){
    window.clearInterval(int1); int1="end";
    if(level["moznosti"]=='dev'){
      int1=false;
      vytvor_laser();
      geto('hra').style.backgroundColor='yellow';
      window.setTimeout("geto('hra').style.backgroundColor='';", 400);
      return;
    }
    
    geto("hra").style.backgroundColor='yellow';
    geto("jmeno_levelu").innerHTML=level["info"]["jmeno"]+" - vyhráno!";
    geto("laser").id=null;
    geto("tl_start").value="Pokračovat do dalšího levelu";
    geto("tl_start").onclick=function (){
      if(window.location.hash) return window.location = "#" + window.prompt("Číslo levelu:");

      write_user((cislo_levelu+1)+";"+barvalaseru+";"+(ctverecky?1:0));
      location.reload(true);
    }
    return;
  }/*výhra*/
  
  for(var i=0;i<level_mapa.length;i++){
    if(x==level_mapa[i][0] && y==level_mapa[i][1]){
      window.clearInterval(int1);
      int1=false;
      vytvor_laser();
      window.setTimeout("geto('hra').style.backgroundColor='#0050FF';", 50);
      window.setTimeout("geto('hra').style.backgroundColor='';", 200);
      return;
    }
  }
  
  for(var i=0;i<level["zrcadla"].length;i++){
    if(x==level["zrcadla"][i][0] && y==level["zrcadla"][i][1]){
      var z=level["zrcadla"][i][2];
      break;
    }
  }//původní zrcadla
  
  if(!z && user_zrcad){
    for(var i=0;i<user_zrcad.length;i++){
      if(x==user_zrcad[i][0] && y==user_zrcad[i][1]){
        var z=user_zrcad[i][2];
        break;
      }
    }//vložená zrcadla
  }
  
  var m_smer=smer;
  smer=false;

  smer=zrcadla[z+"|"+m_smer[0]+";"+m_smer[1]];
  if(!smer) smer=m_smer;
  /* pokud se nenachazi v tabulce zrcadel, tak použije minulý směr*/
  
  x=x+smer[0];
  y=y+smer[1];
  
  var x_px=(x*ctverec)-1;
  var y_px=(y*ctverec)-1;
  
  if(smer[0]==1) x_px-=ctverec;
  if(smer[1]==1) y_px-=ctverec;
  
  if(smer[1]==0) var typ=1;
  else var typ=2;
  
  geto("laser").src=imgpath+barvalaseru+typ+".gif";
  geto("laser").style.left=x_px;
  geto("laser").style.top=y_px;
  geto("laser").typ=typ;
  
  laser=new Array(x,y,typ);
}
/*pohyb laseru*/


var prechod_i=0;
var prechod_smer=1;
function prechod_barev(){
  geto("hra").style.backgroundColor="rgb(200,200,"+(prechod_i*17)+")";
  if(prechod_i==3) prechod_smer=1;
  if(prechod_i==13) prechod_smer=-1;
  prechod_i+=prechod_smer;
}
/*přechod barev*/


function vloz_objekt(x,y,typ,co){
  var x_px=(x*ctverec)-ctverec;
  var y_px=(y*ctverec)-ctverec;
  if(co=="w"){
    var x_px=(x*ctverec)-1;
    var y_px=(y*ctverec)-1;
  }
    
  newImg=document.createElement("img");
  newImg.setAttribute("src",imgpath+co+typ+".gif");
  newImg.setAttribute("alt",x+","+y+","+typ);
  newImg.style.left=x_px;
  newImg.style.top=y_px;
  geto("mapa").appendChild(newImg);
}
/*vloží objekt[0]+","+user_zrcad[k][1]+","+user_zrcad[k][2]*/


function dev_vypisMapu(){
    txt = "";
    for(k in user_zrcad){
        txt += "["+user_zrcad[k]+"], ";
    }
    geto("dev_vypisMapu").innerHTML = txt.substr(0,txt.length-2)
}

function vytvor_hru(){
  geto("hra").innerHTML="<p class=\"fright\"><strong>Autor:</strong> "+level["info"]["autor"]+"</p>";
  geto("hra").innerHTML+="<h2 id=\"jmeno_levelu\">"+level["info"]["jmeno"]+"</h2>";
  geto("hra").innerHTML+="<div class=\"clear\"></div>";
  geto("hra").innerHTML+="<div id=\"misto\"></div> <span id=\"moznosti\"></span> <div class=\"clear\"></div>";
  geto("hra").innerHTML+="<input type=\"button\" value=\"Vypustit laser\" onclick=\"hra_start();\" id=\"tl_start\">";
  if(level["moznosti"]=='dev')
      geto("hra").innerHTML+="<input type=\"button\" value=\"Vypsat zrcadla\" onclick=\"dev_vypisMapu();\"><p id='dev_vypisMapu'></p>";
  /*struktura*/
  
  geto("misto").style.width=level["info"]["pole_x"]*ctverec+1;
  geto("misto").style.height=level["info"]["pole_y"]*ctverec+1;
  /*nastavení rozměrů místa*/
  
  newMap=document.createElement("div");
  newMap.setAttribute("id","mapa");
  newMap.style.width=level["info"]["pole_x"]*ctverec;
  newMap.style.height=level["info"]["pole_y"]*ctverec;
  geto("misto").appendChild(newMap);
  /*vložení mapy do připraveného místa*/
  
  var arr=level["mapa"];
  for(var i=0;i<arr.length; i++){
    x=arr[i][0];
    y=arr[i][1];
    typ=arr[i][2];

    if(isNaN(x) && isNaN(y)){
      alert("Nastala vyjímka v levelu na adrese xb2d5g5a:d5g4 program nebude moci dále pokračovat! :)\nChyba: Zeď v pořadí "+(i+1)+". obsahuje zdvojený limit!");
      return false;
    }
    if(isNaN(x)){
      x1=parseInt(x.split("-",2)[0]);
      x2=parseInt(x.split("-",2)[1]);
      for(x=x1;x<=x2;x++) level_mapa[level_mapa.length]=new Array(x,y,typ);
    }
    else if(isNaN(y)){
      y1=parseInt(y.split("-",2)[0]);
      y2=parseInt(y.split("-",2)[1]);
      for(y=y1;y<=y2;y++) level_mapa[level_mapa.length]=new Array(x,y,typ);
    }
    else{
      level_mapa[level_mapa.length]=new Array(x,y,typ);
    }
  }
  /*rozšíření zdí*/
  
  var arr=level_mapa;
  for(var i=0;i<arr.length; i++) vloz_objekt(arr[i][0],arr[i][1],arr[i][2],"w");
  /*ohraničení (zdi)*/
  
  var arr=level["info"];
  i="start"; vloz_objekt(arr[i][0],arr[i][1],arr[i][2],"s");
  i="cil"; vloz_objekt(arr[i][0],arr[i][1],arr[i][2],"s");
  /*vložení startu a cíle*/
  
  var arr=level["zrcadla"];
  for(var i=0;i<arr.length; i++) vloz_objekt(arr[i][0],arr[i][1],arr[i][2],"m");
  /*vytvoreni zrcadel*/
  
  var arr=level["moznosti"];
  if(arr == 'dev') arr = [1,2,3,4,5,6,7,8,0]; //build mód
  for(var i=0;i<arr.length; i++){
    newImg=document.createElement("img");
    newImg.setAttribute("src",imgpath+"m"+arr[i]+".gif");
    newImg.setAttribute("title","typ: "+arr[i]);
    newImg.setAttribute("alt",arr[i]);
    newImg.className="moznost";
    newImg.onmousedown=function(e) {if(e) event=e; mouse_down(event,this);}
    geto("moznosti").appendChild(newImg);
  } 
  /*možnosti*/
  
  vytvor_laser(); //vytvoření laseru
}
/*inicializace*/


function script_start(){
  geto("texthelp").style.display="none";
  geto("help").onclick=function(){
    var stat=geto("texthelp").style;
    if(stat.display=="none"){
      stat.display="block";
      this.innerHTML="Skrýt nápovědu";
      this.style.borderColor="black";
    }
    else{
      stat.display="none";
      this.innerHTML="Zobrazit nápovědu";
      this.style.borderColor="white";
    }
  }
  
  if(!cislo_levelu){
    geto("hra").innerHTML="<h2>Spustit hru:</h2><p>Nezapomeňte si, prosím, přečíst nápovědu.</p>";
    newObj=document.createElement("input");
    newObj.setAttribute("type","button");
    newObj.setAttribute("value","Spustit hru level po levelu");
    newObj.onclick=function (){
      write_user("1;"+barvalaseru+";"+(ctverecky?1:0));
      location.reload(true);
    }
    geto("hra").appendChild(newObj);
    
    newObj=document.createElement("input");
    newObj.setAttribute("type","button");
    newObj.setAttribute("value","Načíst single level");
    newObj.onclick=function (){
      window.location = "#" + window.prompt("Číslo levelu:");
    }
    geto("hra").appendChild(newObj);
  }
  else if(level["info"]["pole_x"]) vytvor_hru();
  else {
    geto("hra").innerHTML="<h2>Jste absolutní vítěz této hry!</h2><p>Pokud jste nepodváděli, tak <strong>GRATULUJEME</strong>! ;)</p>";
    window.setInterval("prechod_barev()",10);
  }
  /*co necháme ukázat do pole hra*/
  
  
  var prvni_barva=get_user().split(";")[1];
  if(prvni_barva == "r" || prvni_barva == "b") geto("radio_laser_"+prvni_barva).checked=true;
  else geto("radio_laser_r").checked=true;
  /*nastavime prvotní barvu*/
  if(get_user().split(";")[2]=="1") geto("checkbox_pozadi").checked=true; 
  /*zaškrtneme čtverečky*/
  nastaveni();
  /*nastavení nových podmínek*/
}


var ctverecky=false;
var barvalaseru="r";
var rychlost=90;
function nastaveni(){
  if(geto("checkbox_reset").checked){
    write_user();
    location.reload(true);
    return;
  }
  /*resetování nastavení*/
   
  if(geto("checkbox_pozadi").checked){
    if(geto("misto")) geto("misto").className="ctverecky";
    ctverecky=true;
  }
  else {
    if(geto("misto")) geto("misto").className="";
    ctverecky=false;
  }
  /*když zaškrtl a chce zobrazit - zobrazíme*/
  
  if(geto("radio_laser_r").checked){
    barvalaseru="r";
    rychlost=90;
  }
  if(geto("radio_laser_b").checked){
    barvalaseru="b";
    rychlost=50;
  }
  if(geto("laser")) vytvor_laser();
  /*nastavení typu laseru*/
  
  tmp_cislo_levelu = parseInt(get_user().split(";")[0]);
  write_user(tmp_cislo_levelu+";"+barvalaseru+";"+(ctverecky?1:0));
}
/*funkce pro nastaveni*/



function hra_start(){
  if(!int1 && int1!="end"){
    int1=window.setInterval('posun_laser()', rychlost);
  }
  else if(int1!="end"){
    window.clearInterval(int1);
    int1=false;
    vytvor_laser();
  }
}
/* start posouvani laseru*/



function get_user(){
  nazev="lasergame";
  obsah=document.cookie;
  upravene=obsah.split(';');
  velikost=upravene.length;
  kusy=""; vrat="";
  for (x=0;(x<velikost && vrat=="");x++){
    kusy=upravene[x].split('=');
    if(kusy[0].substring(0,1)==' ') kusy[0]=kusy[0].substring(1,kusy[0].length);
    if(kusy[0]==nazev) vrat=kusy[1];
  }
  if(vrat) hodnota=unescape(vrat);
  else hodnota="";
  return hodnota;
}
function write_user(hodnota){
  document.cookie="lasergame="+escape(hodnota)+"; expires=";
}
/*funkce s cookies*/

////////////////////////////////////
/* <- engine hry  |  drag&drop -> */
////////////////////////////////////

  /* ======================== */
  // Drag&drop systém vychází //
  // z řešení Michala Kusýna  //
  /* ======================== */

function pozice_px(object){
  var xPos=object.offsetLeft;
  tempEl=object.offsetParent;
  while(tempEl!=null){
    xPos+=tempEl.offsetLeft;
    tempEl=tempEl.offsetParent;
  }
  var yPos=object.offsetTop;
  tempEl=object.offsetParent;
  while(tempEl!=null){
    yPos+=tempEl.offsetTop;
    tempEl=tempEl.offsetParent;
  }
  return new Array(xPos,yPos);
}//funkce zišťující polohu objektu - (c) Pif


var dragobj; //globální proměnná pro aktuálně přenášený objekt

function mouse_down(event,object){
  if(int1) return;
  /*když je vypuštěný laser, nepřesunujeme*/
  
  var obj_px=pozice_px(object);
  var pole_px=pozice_px(geto("mapa"));
  
  object.style.border="1px red solid";
  
  if(object.parentNode.id!="mapa"){
    if(level["moznosti"]=='dev'){
      object = object.cloneNode(false);
      object.onmousedown=function(e) {if(e) event=e; mouse_down(event,this);}
    }
    else
      geto("moznosti").removeChild(object);
    
    object.style.left=obj_px[0]-pole_px[0]-1;
    object.style.top=obj_px[1]-pole_px[1]-1;
    geto("mapa").appendChild(object);
  /*přesunout objekt s novými vlastnostmi*/
  }
  else {
    for(var i=0;i<user_zrcad.length;i++){
      if(Math.round(parseInt(object.style.left)/ctverec)+1==user_zrcad[i][0] && Math.round(parseInt(object.style.top)/ctverec)+1==user_zrcad[i][1]){
        //když se rovná pozice
        user_zrcad.splice(i,1);
        break;
      }
    }
  }
  /*odebrat původní vložené zrcadlo*/
  
  object.clickX=event.clientX;
	object.clickY=event.clientY;
  /*pamatovat kliknutí myši*/
  
  object.left=parseInt(object.style.left); 
  object.top=parseInt(object.style.top);
  
  dragobj=object;
  /* dáme si id objektu do globální proměnné*/
  
  geto("body").style.cursor="move";
  /* posunovací kurzor*/
  
  if(IE){
    document.attachEvent('onmousemove', mouse_move);
    document.attachEvent('onmouseup', mouse_up);
  }
  if(NS || OPERA){
    document.addEventListener('mousemove', mouse_move, true);
    document.addEventListener('mouseup', mouse_up, true);
  }
  
  return stopEvent(event);
}

function mouse_move(event){
  var posunx=dragobj.left + event.clientX-dragobj.clickX;
  var posuny=dragobj.top + event.clientY-dragobj.clickY;
  
  dragobj.style.left=posunx-(posunx%ctverec)-1; //odečítáme kvuli borderu (později přičtem)
  dragobj.style.top=posuny-(posuny%ctverec)-1;
  
  return stopEvent(event);
}

function mouse_up(event){
  geto("body").style.cursor="";
  /* posunovací kurzor*/
  
  if(IE){
    document.detachEvent('onmousemove', mouse_move);
    document.detachEvent('onmouseup', mouse_up);
  }
  
  if(NS || OPERA){
    document.removeEventListener('mousemove', mouse_move, true);
    document.removeEventListener('mouseup', mouse_up, true);
  }
  
  dragobj.style.top=parseInt(dragobj.style.top);
  dragobj.style.left=parseInt(dragobj.style.left);
  
  var x=Math.round(parseInt(dragobj.style.left)/ctverec)+1; //přičítáme kvuli borderu (dříve jsme odečetli)
  var y=Math.round(parseInt(dragobj.style.top)/ctverec)+1;
  
  for(var i=0;i<level["zrcadla"].length;i++){
    if(x==level["zrcadla"][i][0] && y==level["zrcadla"][i][1]){
      var obsazeno=true;
      break;
    }
  }//původní zrcadla
  
  if(!obsazeno){
    for(var i=0;i<user_zrcad.length;i++){
      if(x==user_zrcad[i][0] && y==user_zrcad[i][1]){
        var obsazeno=true;
        break;
      }
    }//vložená zrcadla
  }
  
  if((x > 0 && x < level["info"]["pole_x"]) && (y > 0 && y < level["info"]["pole_y"]) && (!obsazeno)){
    dragobj.style.border="";
    user_zrcad[user_zrcad.length]=[x,y,dragobj.alt];
  }
  else{
    geto("mapa").removeChild(dragobj);
    geto("moznosti").appendChild(dragobj);
    dragobj.style.border="1px black solid";
  }
  return stopEvent(event);
}

function stopEvent(event){
	if(IE) {event.cancelBubble = true; return false;}
	if(NS || OPERA) {event.stopPropagation(); event.preventDefault(); return false;}
}

