

/* ---- MAPA ---- */
String.prototype.px = function() {
    return this.substr(0, this.length-2)*1;    
}
            
var _cont;
var _mapa;
var _mapaB;
var _debug;
var _info;
var _main;
var jg;

var pinBox = Array();
var pinBoxD = Array();
                  
var boxWidth = 0;
var boxHeight = 0;

var mapsM = Array(3,5);
var mapsM3 = Array(1217,771);
var mapsM5 = Array(4866,3083);

var mapsMM = 4;

var defMapaL = 0;

var mapCols = 0;
var mapRows = 0;  
var loadedM;

var mapLeft = 0;
var mapRight = 0;
var mapWidth = 800;
var mapHeight = 577;
var mapPath = "/";

var moveSpeed = _admin ? 50 : 500;
var moveStop = false;

/* pocet boxu viditelnych */
var boxCL = boxCR = 0;   
var _admin = true;  

function initMap(bw,bh,cols,rows,zoom) {

    _admin = false;
	if (zoom!=undefined) { defMapaL = zoom; }
    initMapA(bw,bh,cols,rows,0,'/');
}

function toggleZ(a,b) {
	z1 = a.css("z-index");
	z2 = b.css("z-index");

	if (z1<z2) {
		a.css("z-index",z2);
		b.css("z-index",z1);
	}
}

var isIE;
function getIE() {
	jQuery.each(jQuery.browser, function(i, val) {
		switch (i) {
		case "msie":
			isIE = val;
			break;
		}
    });
}
getIE();

function resizeMap(w) {

	if (_admin || _print) { return 0; }

    mapWidth = w; //_mapa.width();
    //_mapaB.css("width",mapWidth+"px");

    _mapaB.css("width",mapWidth+"px");
    _mapaB.css("height",mapHeight+"px"); 
                              
    boxCL = Math.ceil((mapWidth+2)/boxWidth);
    boxCH = Math.ceil((mapHeight+2)/boxHeight);

    _mapa.css("height",mapHeight+"px"); 
    _mapa.css("width",mapWidth+"px");  
}
                 
function initMapA(bw,bh,cols,rows,width,path) {


	jg = new jsGraphics("ptrail");
	if (_print) { jg.setPrintable(true); }

	_cont = $("#mcontainer");
	_main = $("#mcnt");
	_mapa = $("#mapa");
	_mapaB = $("#mapaB");
	_debug = $("#debug");
	_info = $("#info");

    boxWidth = bw;
    boxHeight = bh;
    mapCols = cols;
    mapRows = rows;  
    
    mapPath = path;
    
    if (width==0) {
        mapWidth = _mapa.width(); 
    } else {
        mapWidth = width;
    }    

    _mapa.css("height",mapHeight+"px"); 
    _mapa.css("width",mapWidth+"px"); 
    _mapa.disableTextSelect();
    
                              
    boxCL = Math.ceil((mapWidth+2)/boxWidth);
    boxCH = Math.ceil((mapHeight+2)/boxHeight);
    
    _mapaB.css("width",mapWidth+"px");
    _mapaB.css("height",mapHeight+"px");  
    
	_main.click(function() {
		$("#loadM").hide();
		$("#loadL").hide();
		clearMapImg();
		actLoadTyp = -1; //kvuli nahravani AJAXem
	});

	if (!isIE) {
	    _mapa.mouseup(function(){   		
			toggleZ(_mapa,_mapaB);
	        stopDrag();             
	    }).mousedown(function(){ 
			//toggleZ(_mapaB,_mapa); 
	        startDrag();               
	    });
	} else {
		toggleZ(_mapaB,_mapa);
	}

    _mapaB.mouseup(function(){ 
		if (!isIE) { toggleZ(_mapa,_mapaB); }
        stopDrag();             
    }).mousedown(function(){   
        startDrag();               
    });

	var mdbl;
	if (isIE) { mdbl = _mapaB; } else { mdbl = _mapa; }
    mdbl.dblclick(function(e) {  
        pos = _mapaB.offset();    
        posX = e.pageX-pos.left-_cont.css("left").px();
        posY = e.pageY-pos.top-_cont.css("top").px();   
                
        _debug.text("doubleClick "+posX+":"+posY);  

        if (_admin) {

            $("#mx").attr("value",posX);
            $("#my").attr("value",posY);
            
            addPoint(posX,posY,0,'BOD');
            
            trasa = $("#mtyp").attr("checked");
            if (trasa!=true) {
                m = $("#mmap");
                m.val(m.val()+";"+posX+","+posY); 
                
                ptsX[ptsX.length] = posX;
                ptsY[ptsY.length] = posY;
                drawPath(ptsX,ptsY);
            }
        } else {
            if (defMapaL!=1) {
                mapZoom(1,false); 
                moveMapToO(posX*mapsMM,posY*mapsMM,e.pageX-pos.left,e.pageY-pos.top);  
            }
        }   
          
    });    
    
    $().keydown(function (e) {
      _debug.text("keydown: "+e.which);    
        
      switch (e.which) {
      case 40:  moveMap("key",0,-boxHeight); break;  
      case 38:  moveMap("key",0,boxHeight); break;  
      case 37:  moveMap("key",-boxWidth,0); break;  
      case 39:  moveMap("key",boxWidth,0); break;           
      } 
    });
    $().keyup(function (e) {
      _debug.text("keyup: "+e.which);   
    });
                                                     
    if (mapSetX==undefined) { mapSetX = 0; }         
    if (mapSetY==undefined) { mapSetY = 0; } 

	loadedM = true;

	clearMapImg();
	setMapTo(mapSetX,mapSetY);
    
    //activateBox(0,0);

    $("#bup").click(function(){ moveMap("up"); });
    $("#bdown").click(function(){ moveMap("down"); });
    $("#bleft").click(function(){ moveMap("left"); });
    $("#bright").click(function(){ moveMap("right"); });

	readPins();



}  

function mapZoom(dir,move) {
    d = defMapaL;
    defMapaL += dir;    

    if (defMapaL<0) { defMapaL = 0; }
    if (defMapaL>=mapsM.length-1) { defMapaL = mapsM.length-1; }

	if (d==defMapaL) { return 0; }
    
    if (move==undefined) {
        mapLeft = _cont.css("left").px();
        mapTop = _cont.css("top").px();

        switch (defMapaL) {
        case 1:      
            posX = Math.round((-mapLeft+mapWidth/2)*mapsMM);
            posY = Math.round((-mapTop+mapHeight/2)*mapsMM);                      
            break;
        case 0:
            posX = Math.round(mapLeft/mapsMM);
            posY = Math.round(mapTop/mapsMM);
            break;
        }
     
        moveMapTo(posX,posY,true); 
    }
	clearPoints();
    clearMapImg();  	  
    activateBox(0,0);
	

	addHistory();
}

function setMap(map) { defMapaL = map; }

function clearMapImg() {

    loaded = Array(mapRows);
    for (i=0; i<mapRows; i++) {
        loaded[i] = Array(mapCols);
        for (j=0; j<mapCols; j++) {
            loaded[i][j] = 0;
        }
    }  
}
     
function loadTrasa(id,title,img,typ,move) { 
	actLoadTyp = -1;
    $("#loadP>div").load("/ajax/get-trasa/?id="+id, {}, function(res) { 
        $(this).html("&nbsp;");
        var trasa = res.split("||");

		if (move==undefined) {
			addPointZ(trasa[0],trasa[1],id,title,img,typ);
		} else {
			addPointM(trasa[0],trasa[1],id,title,true,img,typ);
		}

        if (trasa.length>0) { // && defMapaL==1
            tX = trasa[2].split(",");
            tY = trasa[3].split(",");
            
            lX = Array();
            lY = Array(); 
            for (i=0; i<tX.length; i++) {
	                //lX[i] = tX[i]*1;
	                //lY[i] = tY[i]*1;  

					if (tX[i]!='#') {     
				    	lX[i] = convertXY(tX[i]*1);
				    	lY[i] = convertXY(tY[i]*1);    
					}
            }             

            drawPath(lX,lY,false,typ);  
        }      
    });  
}  
     
function loadTrasaQ(id,title,img,typ) { 
	actLoadTyp = -1;
	//if (defMapaL==1) {
    $("#loadP>div").load("/ajax/get-trasa/?id="+id, {}, function(res) { 
        $(this).html("&nbsp;");
		
        var trasa = res.split("||");        
        if (trasa.length>3) {

	        tX = trasa[2].split(",");
	        tY = trasa[3].split(",");
	            
	        lX = Array();
	        lY = Array(); 
	        for (i=0; i<tX.length; i++) {
	                //lX[i] = tX[i]*1;
	                //lY[i] = tY[i]*1;    
    
				    lX[i] = convertXY(tX[i]*1);
				    lY[i] = convertXY(tY[i]*1);        
	        }             
	            
	        drawPath(lX,lY,true,typ);  
    	}
    }); 
	//} 
}  

function convertXY(a) {
    if (defMapaL==0) {
        return Math.round(a/mapsMM);
    }          
    return a;  
}   

function setMapTo(x,y,fast) { 
    if (x>0) { x *= -1; }
    if (y>0) { y *= -1; }
    
    moveMap("positionF",x,y);    
}   
  
function moveMapTo(x,y,fast) { 
    if (x>0) { x *= -1; }
    if (y>0) { y *= -1; }
    
    x = convertXY(x);
    y = convertXY(y);
    
    if (fast==undefined) {
        res = moveMap("position",x+mapWidth/2,y+mapHeight/2);    
    } else {  
        res = moveMap("positionF",x+mapWidth/2,y+mapHeight/2);  
    }

	return res;
}   
     
function moveMapToO(x,y,ox,oy) { 
    if (x>0) { x *= -1; }
    if (y>0) { y *= -1; }
    
    x = convertXY(x);
    y = convertXY(y);

    moveMap("positionF",x+ox,y+oy);  
}  

var lastDetail = -1;
function showDetail(x,y,id) {	

	hideDetail();

    x = convertXY(x);
    y = convertXY(y);
	$("#ptd").hide();

	toggleZ($("#ptd"),$("#pts"));

  	mapLeft = _cont.css("left").px();
  	mapTop = _cont.css("top").px();

	$("#ptd").load("/ajax/get-detail/?id="+id+"&zoom="+defMapaL+"&mapx="+mapLeft+"&mapy="+mapTop,{},function() { 


		lastDetail = id;
		$("#pt"+id).hide();
		$("#ptp"+id).hide();

		$(".ptDetail").css("left",(x-5)+"px");
    	$(".ptDetail").css("top",(y+10)+"px"); 

		$(".ptDetail>div").hide();
		$("#ptd").show();
		$(".ptDetail>div").show(1000);

		$("#detClose").click(function() { 
			
			if (defMapaL==1) {
				$("#ptp"+id).show();
			}
			$("#pt"+id).show(); 
			hideDetail(); 
		});

	});
}

function printActualMap() {

  	mapLeft = _cont.css("left").px();
  	mapTop = _cont.css("top").px();
	openWindow("/cz/?print=true&r=true&zoom="+defMapaL+"&mapx="+mapLeft+"&mapy="+mapTop+"#"+historyLink,'mp',900,700);
}

function hideDetail() {	

	$("#pt"+lastDetail).show();
	toggleZ($("#pts"),$("#ptd"));
	$("#ptd").html("&nbsp;");
	lastDetail = -1;
}

function readPoints(id,ln) {
	if (id>0) {
		$("#loadM>div").load("/ajax/get-point/?ln="+ln+"&lp=true&id="+id,{},function() { 	
		});
	}
	
}

function pinUp(id) {		
	$("#ptp"+id).toggleClass("active");	
	addPin(id);
}

function addPin(id,f) {

	if (f==undefined) {
		removePin(id);
		var cls = $("#ptp"+id).hasClass("active");
		if (cls) {
			pinBox[pinBox.length] = id;
		}
	} else {
		pinBox[pinBox.length] = id;
	}
	createCookie('pinS',pinBox);

}

function removePin(id) {
	var l = pinBox;
	pinBox = Array();
	for (i=0; i<l.length; i++) {
		if (l[i]!=id && l[i]>0) { pinBox[i] = l[i]; } else { eraseCookie('pinID'+id); }
	}
}

function readPins() {

	var p;
	p = readCookie('pinS');

	$("#loadM>div").load("/ajax/load-pins/?id="+p,{},function() { 
		pinBox = Array();
		if (p!=null && p!=undefined) {
			p = p.split(',');
			for (var i=0; i<p.length; i++) {
				pinBox[pinBox.length] = p[i];
			}		
		}
		drawPins();
		createCookie('pinS',pinBox);
	});

	
}

function drawPins() {

	for (i=0; i<pinBox.length; i++) {
		if (pinBox[i]>0) {
			var p = pinBoxD[pinBox[i]];

			createCookie('pinID'+pinBox[i],p);
			if (p[6]=='') { 
				addPointEx(p[0]*1,p[1]*1,p[2]*1,p[3],false,p[4]*1,false,p[5]*1,true);
			} else {
				addPointEx(p[0]*1,p[1]*1,p[2]*1,p[3],false,p[4]*1,false,p[5]*1,true);
				loadTrasaQ(p[2]*1,p[3],p[4]*1,p[5]*1);
			}
			$("#ptp"+p[2]).addClass("active");			
		}	
	}
	pinAll();
}

function pinAll() {
	$(".ptPin").unbind("click");
	$(".ptPin").click(function() { 
		var id = $(this).attr("id").substr(3,10);
	 	pinUp(id*1);  
	})
}

function addPointEx(x,y,id,title,clear,img,move,typ,force) {	
    
	if (force!=true && jQuery.inArray(id,pinBox)!=-1) { 
		if (move==true) {
			moveMapTo(x,y);
		}
		return 0; 
	}

	if (clear==undefined || clear==true) {
		actLoadTyp = -1;
		clearPoints();
	}

	
	var lx = x;
	var ly = y;
    x = convertXY(x);
    y = convertXY(y);

	if (img>0) { imgH = '<img src="/data/novopacko/'+id+'-ico/foto.jpg" alt="'+title+'" />'; 
		} else { imgH = '<img src="/img/blank.gif" alt="'+title+'" />'; }
	if (defMapaL==1) { ptpX = x; large = 'class="ptSpan l" '; } else { ptpX = x-68; large = 'class="ptSpan" '; }

	if (typ!=undefined) { largeB = " b"; } else { largeB = ""; typ = 0; }

    $("#pts").html($("#pts").html()+'<span '+large+' id="ptTyp'+typ+'"><a href="javascript:showDetail('+lx+','+ly+','+id+');" id="pt'+id+'" class="point'+largeB+'" title="'+title+'">'+imgH+'<span>'+title+'</span></a><a href="javascript:void(0);" id="ptp'+id+'" title="Uložit" class="ptPin"><img src="/img/pin.png" alt="Vyznačit objekt na mapě" /></a></span>');    
    
	if (jQuery.inArray(id,pinBoxD)==-1) {
		pinBoxD[id] = Array(lx,ly,id,title,img,typ);	
	}


	$("#pt"+id).css("left",(x-39)+"px");
    $("#pt"+id).css("top",(y-62)+"px"); 
	
    $("#ptp"+id).css("left",(ptpX+60)+"px");
    $("#ptp"+id).css("top",(y-100)+"px");  

	pinAll();

	if (move==true || move=="fast") {
		if (move=="fast") {
			moveMapTo(x,y,true);
		} else {
			moveMapTo(x,y);
		}

	}

}

function addPoint(x,y,id,title,img) { 
	addPointEx(x,y,id,title,true,img,true);
}

// staticke zobrazeni bohu s pohybem
function addPointZ(x,y,id,title,img,typ) { 

	res = moveMapTo(x,y);

	historyPt = id;
	addHistory(res[0],res[1]);

    addPointEx(x,y,id,title,true,img,false,typ);	
}
// staticke zobrazeni bohu bez pohybu
function addPointM(x,y,id,title,clear,img,typ) { 
    addPointEx(x,y,id,title,clear,img,false,typ);
}

function clearPoints() {

	if (loadedM) {
	    clearPath();
	    $("#pts").html("");
		hideDetail();
		drawPins();
	}
}

function getBoundsX(left) {  
	var d = mapsM[defMapaL]
	var mx;
	eval("mx = mapsM"+d+";");

    //mapCols*boxWidth;

    var max = -(mx[0]-mapWidth); //-20;
	if (max>0) { max = 0; }
       
    if (left>0) { return 0; }                    
    if (left<max) { return max; }
    return left;       
}

function getBoundsY(top) {  
	var d = mapsM[defMapaL]
	var mx;
	eval("mx = mapsM"+d+";");

  	//mapRows*boxHeight   
    var max = -(mx[1]-mapHeight);
    
    if (top>0) { return 0; }                         
    if (top<max) { return max; }
    
    return top;
}

function activateBox(left,top) {    
    $(".cell").removeClass("active");
    var vLF = vHF = 0;
                                 
    vLF = -Math.floor(left/boxWidth);
    vHF = -Math.floor(top/boxHeight);             
           
    for (i=vLF-1; i<=vLF+boxCL; i++) {
        for (j=vHF-1; j<=vHF+boxCH; j++) {                                
            if (i>=0 && j>=0 && j<mapRows && i<mapCols) {                               
                $("#bn"+j+"_"+i).addClass("active"); 
                loadImg("#bn"+j+"_"+i,i,j);
            }
        }
    }     
}

function loadImg(obj,x,y) { 
    var d = mapsM[defMapaL];
    if (loaded[y][x]!=1) {

        $(obj+">span").attr("style","background:url("+mapPath+"mapa/"+d+"/"+d+"-"+x+"-"+y+".jpg) left top no-repeat;");
		$(obj+">span").html("<img src=\""+mapPath+"mapa/"+d+"/"+d+"-"+x+"-"+y+".jpg\" />");
        loaded[y][x] = 1;
    }
}

var dragX = startDragX = dragMapX = null;
var dragY = startDragY = dragMapY = null;
var drag = false;

function startDrag() {       
  
        dragMapX = _cont.css("left").px();
        dragMapY = _cont.css("top").px();

		if (isIE) { dr = _mapaB; } else { dr = _mapa; }
            
        dr.addClass("drag");
        dr.mousemove(function(e) {
                dragX = e.pageX;
                dragY = e.pageY; 
                
                if (startDragX == null) {
                    startDragX = dragX;
                    startDragY = dragY;
                }
                
                l = (startDragX-dragX);
                t = (startDragY-dragY);
                
                moveMap("drag",l,t);
                _debug.text("dragStart: "+l+":"+t); 

         });                     
}

function stopDrag() { 
        dragX = startDragX = null;
        dragY = startDragY = null;  

		if (isIE) { dr = _mapaB; } else { dr = _mapa; }

        _debug.text("dragStop");
        moveStop = false;
        dr.removeClass("drag");   
        dr.unbind('mousemove');

		addHistory();         
}
         
function moveMap(dir,x,y) {  
    
  mapLeft = _cont.css("left").px();
  mapTop = _cont.css("top").px();
  
  var mL, mT;
                                                  
  if (!moveStop || dir=="drag" || dir=="position") {
      moveStop = true;
                
      mL = mapLeft;
      mT = mapTop;

	  moveA = _admin ? 4*boxHeight : boxHeight;
      
      var anParam;      
      switch (dir) {
      case "key":               
      case "drag":  
        break;
      case "up":
        anParam = { top: (mT = getBoundsY(mapTop-moveA))+"px"};                                                             
        break;
      case "down":
        anParam = { top: (mT = getBoundsY(mapTop+moveA))+"px"};      
        break;
      case "left":
        anParam = { left: (mL = getBoundsX(mapLeft-moveA))+"px"};                                                               
        break;
      case "right":
        anParam = { left: (mL = getBoundsX(mapLeft+moveA))+"px"};                                                               
        break;  
      } 
      
	  if (dir!="positionF") {
      	activateBox(mL,mT);
	  }
                      
      switch (dir) {
      case "positionF":  
        anParam = { left: (mL = getBoundsX(x))+"px", top: (mT = getBoundsY(y))+"px"};             
        _cont.animate( anParam, 1, "linear", function() { moveStop=false; } ); 
        activateBox(x,y);
 
        break;
      case "position":  
        anParam = { left: (mL = getBoundsX(x))+"px", top: (mT = getBoundsY(y))+"px"};             
        _cont.animate( anParam, moveSpeed, "linear", function() { moveStop=false; } ); 
        activateBox(x,y);
		
        break;
      case "key":  
        anParam = { left: (mL = getBoundsX(mapLeft-x))+"px", top: (mT = getBoundsY(mapTop+y))+"px"}; 
        _cont.animate( anParam, moveSpeed, "linear", function() { moveStop=false; } ); 
 
        break;             
      case "drag": 
         _info.text("moving: "+x+":"+y); 
        _cont.css("left",getBoundsX(dragMapX-x)+"px");
        _cont.css("top",getBoundsY(dragMapY-y)+"px");  
        break; 
      case "up":
      case "down": 
      case "left":
      case "right":           
        _cont.animate( anParam, moveSpeed, "linear", function() { moveStop=false; } );
		
		addHistory(); 
        break;  
      } 	  	


   }  

   return Array(Math.round(mL),Math.round(mT));      
   
}     

var srchBox = $("#srch");
var srchBoxH = $("#srchH");

function srchHide() {
    srchBox.animate( {left: "-250px"}, 250, "linear", function() { srchBoxH.hide(); } );
}

function srchShow() { 
    srchBoxH.show();
    srchBox.animate( {left: "0px"}, 250, "linear", function() {  } );
}

function srch() {
    if (srchBox.css("left")=="0px") {
        srchHide();
    } else {
        srchShow();
    }
} 


/* --- GR ---- */

var pathColor = Array();
pathColor[50] = "fff600";
pathColor[51] = "e84c00";
pathColor[53] = "2bde01";
pathColor[11] = "ba3000";


function drawPath(x,y,clear,typ) { 
	  if (clear==undefined || clear==false) {
      	jg.clear();
	  }
	  
	  if (pathColor[typ]==undefined) { col = "ff0000"; } else { col = pathColor[typ]; }
	  if (_print) { col = "000000"; }
      jg.setColor("#"+col); 

	  //if (_print) {
	//	  jg.setStroke(3);	
	  //} else {
		  if (defMapaL==1) {
	         jg.setStroke(8);                        
		  } else {
	         jg.setStroke(5);                        
		  }
	  //}
      jg.drawPolyline(x,y);           
      jg.paint(); 
}  
function clearPath() {   
      jg.clear();  
}  

    
