//Class de Mapas
//declaring the class
var clsMapa = Class.create();

//defining the rest of the class implmentation
clsMapa.prototype = {

	initialize: function(div,img) 
	{
		//props basicas
		this.div = div;		//id do div contentor
		this.img = img;     //id da imagem
		this.src = $(img).src;
		this.mapaImg = new Image();  //nova prop para detectar nova imagem
		this.legendSrc = $("LEGEND").src;
		this.velhasrc = '';
		this.width = ($(img).style.width).replace(/px/gi,'');
		this.height = ($(img).style.height).replace(/px/gi,'');
		this.extent = new clsExtent(0,0,0,0);
		this.layers = [];
		this.posx = findPosX($(img));  //guardam a posição original da img
		this.posy = findPosY($(img));
		this.persist = new clsPersist();
		
		//efeitos
  		//this.fxSubstMapa = new fx.Opacity(div, {duration: 300});
  		this.fxHideMapa = function() {return new fx.Height(this.div , {duration: 200});};
		//eventos
		//para subst da img só depois de carregada, e retirar o waiting
		//var mself = this;
		//addEvent($(img),'load',function() {mself.trocaImg.call(mself);});  //evitar a perda de scope do objecto this!

	},
	
	actualizaImg: function(novaImagem) 
 	{  //chamado externamente para actualizar a img do mapa
 		delete this.mapaImg;
		this.mapaImg = new Image();
		this.mapaImg.src = novaImagem;
		 
		var iAlt = parseInt(this.height);
		log('opcao = ' + option);

		var novoFx = this.fxHideMapa();
		if(toolbar_id == 'PAN') {
			novoFx.hide();
		} else {			
   			novoFx.toggle();
		}
  		log('<b>imagem velha escondida</b>');
  		
  		//colocar a img no seu sítio original (caso do pan!)
  		$(this.img).style.left = 0 + 'px'; $(this.img).style.top = 0 + 'px';
  		
		//trocar pela nova imagem
  		this.velhasrc = this.src;
		var mself = this;
		//usar um delay para os casos de cache e intranet
		window.setTimeout(function(){mself.trocaImg.call(mself);},200);
 	},
	
	trocaImg: function() 
 	{
		//verificar se a nova imagem já foi carregada
		if(!this.mapaImg.complete) {
			//log('Imagem ainda não recebida...');
			var mself = this;
			window.setTimeout(function(){mself.trocaImg.call(mself);},100);
			return false;
		}
		log('Imagem recebida...mostrar.');
		$(this.img).src = this.mapaImg.src;
		this.src = this.mapaImg.src; 		
		
		var novoFx = this.fxHideMapa();
		var iAlt = parseInt(this.height);
		novoFx.custom(0, iAlt);  //não usar .show() porque aumenta margem inferior do div!
  		toggleWait('off');  //retira o loading
 	},
	
	actualizaImg2: function(novaImagem) 
 	{  //chamado externamente para actualizar a img do mapa
		var iAlt = parseInt(this.height);
		log('opcao = ' + option);
		if(toolbar_id == 'PAN')
   			this.fxHideMapa.hide ();
  		else {			
			log('<b>imagem velha escondida</b>');
   			this.fxHideMapa.custom(iAlt,0);
			}
  		
  		
  		//this.fxSubstMapa.hide();
  		//colocar a img no seu sítio original (caso do pan!)
  		log('posXY:' + findPosX($(this.img)) + ',' + findPosY($(this.img)));
  		$( this.img).style.left = 0 + 'px'; $(this.img).style.top = 0 + 'px';
  		log('posXY:' + findPosX($(this.img)) + ',' + findPosY($(this.img)));
  		this.velhasrc = this.src;
  		/*$(this.img).src = novaImagem;
  		this.src = novaImagem;
		//colocado aqui para funcionar na intranet onde o evento poderá ser rápido demais
		var mself = this;
		$(this.img).onload = function() {mself.trocaImg.call(mself);};*/
		//alternativa ao evento onload da imagem que não é fiável na intranet
		this.trocaImg();
 	},
 	
 	trocaImg2: function() 
 	{
  		log('img recebida: a trocar img');
  		this.fxHideMapa.show();
  		//var iAlt = parseInt(this.height);
  		//this.fxHideMapa.custom(0,iAlt);
  		//this.fxSubstMapa.custom(0,1);
  		toggleWait('off');  //retira o loading
		//retirar o evento para que funcione na intranet
		$(this.img).onload = '';
 	},
	
	actualizaLegend: function(novaLegenda) 
	{
		this.legendSrc = novaLegenda;
		$("LEGEND").src = novaLegenda;
	},
	
	actualizaExt: function(objNovoExt)
	{  
		//actualiza o extent com novos limites xmin, etc, e guarda o anterior	
		log('mudar extent...');
		this.extent.salva();
		this.extent.copia(objNovoExt);
	},
	
	getObjAJAX: function() 
	{ //devolve objecto pronto a transmitir via AJAX/JSON
		var objSoProps = new Object;
		//objSoProps.div = this.div;
		//objSoProps.img = this.img;
		objSoProps.src = this.src;
		//objSoProps.legendSrc = this.legendSrc;
		//objSoProps.velhasrc = this.novasrc;
		objSoProps.width = this.width;
		objSoProps.height = this.height;
		objSoProps.extent = this.extent;
		objSoProps.layers = this.layers;
		objSoProps.persist = this.persist;		
		return objSoProps;
	},
	
	actualizaJSON: function(objJSON)
	{  //recebe um obj JSON, e actualiza params todos
					
		if("mapa" in objJSON) var novoMapa = objJSON.mapa;
			
		
		if("src" in novoMapa)
		{
			this.actualizaImg(novoMapa.src); 
			log('nova src:' + novoMapa.src); 
		}
				
		if("legendSrc" in novoMapa)
		{
			this.actualizaLegend(novoMapa.legendSrc); 
		}
		
		if("extent" in novoMapa)
		{
			var func = objJSON.funcao;
			this.actualizaExt(novoMapa.extent);
			
			if (func != 'PAN' && func != 'PANN' && func != 'PANS' &&func != 'PANO' &&func != 'PANE')
				this.extent.actualizaEscala();

			log('novo xmin:' + novoMapa.extent.xmin);
		}
						
		if("layers" in novoMapa)
		{
			this.layers = novoMapa.layers; 
			log('layers:' + novoMapa.layers); 
		}
				
		if("result" in novoMapa)
		{
			this.result = novoMapa.result; 
			log('layers:' + novoMapa.result);
		}			
	},
	
	isEventOverMap: function(pagX, pagY)
	{
		var limX = parseInt(this.posx) + parseInt(this.width);
		var limY = parseInt(this.posy) + parseInt(this.height);
		if (pagX <= this.posx || pagY <= this.posy || pagX > (limX) || pagY > (limY))
		{
			 return false;
		} 
		else { return true; }
	},

	getPTGeog: function(ratoX,ratoY) 
	{
	//converte 1 ponto na imagem num ponto geográfico
		var oPt = new clsPonto(0,0);
		var mporPixX = this.extent.width / this.width;
		var mporPixY = this.extent.height / this.height;
		var ImgX = ratoX - this.posx;
		var ImgY = this.height - (ratoY - this.posy);  //inverter Y
		
		oPt.x = parseInt(mporPixX * ImgX + parseInt(this.extent.xmin));
		oPt.y = parseInt(mporPixY * ImgY + parseInt(this.extent.ymin));
		return oPt;
	},
	getPTWGS84: function(ratoX,ratoY) 
	{
	//converte 1 ponto na imagem num ponto geográfico em WGS84 (DC-Ago08)
		var oPt = new clsPonto(0,0);
		with(this.extent)
		{
		    var LLwidth=lonmax-lonmin;
		    var LLheight=latmax-latmin;
		}
		var mporPixX = LLwidth / this.width;
		var mporPixY = LLheight / this.height;
		var ImgX = ratoX - this.posx;
		var ImgY = this.height - (ratoY - this.posy);  //inverter Y
		
		oPt.x = mporPixX * ImgX + this.extent.lonmin;
		oPt.y = mporPixY * ImgY + this.extent.latmin;
		return oPt;
	},
	getMailArgs: function()
	{
	//devolve os argumentos para o CdE ser chamado por url!
		var oArgs = {};
		oArgs.xmin = this.extent.xmin;
		oArgs.ymin = this.extent.ymin;
		oArgs.xmax = this.extent.xmax;
		oArgs.ymax = this.extent.ymax;
		//oArgs.layers = this.layers;
		var sArgs = JSON.stringify(oArgs);
		sArgs = sArgs.replace (/"/g, "");	//retirar aspas que bloqueiam este pedido (rect)
		return 'rect=' + sArgs;
	}
};	

var clsPonto = Class.create();

//defining the rest of the class implmentation
clsPonto.prototype = {

	initialize: function(xcoord,ycoord)
	{
		this.x = xcoord;
		this.y = ycoord;
	}
};

var clsExtent = Class.create();

//defining the rest of the class implmentation
clsExtent.prototype = {

	initialize: function(xmin,ymin,xmax,ymax) {
		this.xmin = xmin;
		this.ymin = ymin;
		this.xmax = xmax;
		this.ymax = ymax;
		this.xminant = 0;
		this.yminant = 0;
		this.xmaxant = 0;
		this.ymaxant = 0;
		this.width = xmax-xmin;
		this.height = ymax-ymin;
		this.ratio = (this.height == 0 ? 0: this.width / this.height);
		//adicionado para manter coords em WGS84
		this.lonmin=0;this.latmin=0;this.lonmax=0;this.latmax=0;
	},
	
	salva: function()
	{
		with (this) 
		{
			xminant=xmin;yminant=ymin;xmaxant=xmax;ymaxant=ymax; 
		}
	},
	
	copia: function(objNovoLim)
	{
		//actualiza xmin,xmax, etc.
		with(objNovoLim)
		{
			this.xmin = xmin;
			this.xmax = xmax;
			this.ymin = ymin;
			this.ymax = ymax;
			this.width = Math.abs(xmax - xmin);
			this.height = Math.abs(ymax - ymin);
			//adicionado para manter coords WGS84
			this.lonmin=lonmin;this.latmin=latmin;this.lonmax=lonmax;this.latmax=latmax;
		}

	},

	actualizaEscala: function()
	{
		//Actualiza a escala gráfica
		dx = Math.abs(this.xmax-this.xmin);
		$("escalaGrafica").innerHTML = parseInt(dx * 39 / mMapa.width) + " m";
		
		//Actualiza a escala numerica
		var dblTempScaleFactor = dx /  mMapa.width;
		var dblPixelsPerInch = 96.0;
		var dblMetersPerInch = 0.0254;
		var dblPixelsPerMeter = dblPixelsPerInch / dblMetersPerInch;
		var dblRelativeScale = parseInt(dblTempScaleFactor * dblPixelsPerMeter);
		var strRelativeScale = dblRelativeScale.toString(10);	
		$("escalaNumerica").innerHTML = strRelativeScale;

	},
	
	getRatio: function() {
		this.ratio = (this.height == 0 ? 0: this.width / this.height);
		return this.ratio;
	}
};

var clsPersist  = Class.create();

//defining the rest of the class implmentation
clsPersist.prototype = {

	initialize: function()
	{
		this.percurso = new clsPercurso();
		this.pesquisaPI = new clsPesquisaPI();
		this.pesquisaProximidade = new clsPesquisaProximidade();
		this.GPS = new clsGPS();
	},
	
	updatePercurso: function(perc)
	{
		this.percurso.update(perc);
	},
	
	updatePesquisaPI: function(concelho,subcat,designa,idsig)
	{
		this.pesquisaPI.update(concelho,subcat,designa,idsig);
	},
	
	updatePesquisaProximidade: function(xPoint,yPoint,subcat,buffer,idsig)
	{
		this.pesquisaProximidade.update(xPoint,yPoint,subcat,buffer,idsig);
	},

	updateGPS: function(format,system,show,name)
	{
		this.GPS.update(format,system,show,name);
	},
	
	updateShowGPS: function(show)
	{
		this.GPS.updateShow(show);
	}

};

var clsPercurso  = Class.create();

//defining the rest of the class implmentation
clsPercurso.prototype = {

	initialize: function()
	{
		this.perc = '';
	},
	
	update: function(perc)
	{
		this.perc = perc;
	}
};

var clsPesquisaPI  = Class.create();

//defining the rest of the class implmentation
clsPesquisaPI.prototype = {

	initialize: function()
	{
		this.concelho = '';
		this.subcat = '';
		this.designa = '';
		this.idsig = '';
	},
	
	update: function(concelho,subcat,designa,idsig)
	{
		this.concelho = concelho;
		this.subcat = subcat;
		this.designa = designa;
		this.idsig = idsig;
	}
};

var clsPesquisaProximidade  = Class.create();

//defining the rest of the class implmentation
clsPesquisaProximidade.prototype = {

	initialize: function()
	{
		this.xPoint = '';
		this.yPoint = '';
		this.subcat = '';
		this.buffer = '';
		this.idsig  = '';
	},
	
	update: function(xPoint,yPoint,subcat,buffer,idsig)
	{
		this.xPoint = xPoint;
		this.yPoint = yPoint;
		this.subcat = subcat;
		this.buffer = buffer;
		this.idsig  = idsig;
	}
};

var clsGPS  = Class.create();

//defining the rest of the class implmentation
clsGPS.prototype = {

	initialize: function()
	{
		this.fileFormat = '';
		this.fileSystem = '';
		this.fileShow = undefined;
		this.fileName = '';
	},
	
	update: function(format,system,show,name)
	{
		this.fileFormat = format;
		this.fileSystem = system;
		this.fileShow = show;
		this.fileName = name;
	},

	updateShow: function(show)
	{
		this.fileShow = show;
	}
};
