window.dhtmlHistory.create({
	toJSON: function(o) {
		return Object.toJSON(o);
	}, 
	fromJSON: function(s) {
		return s.evalJSON();
	},
	blankURL: '/js/blank.html?'
	//,debugMode: true
});

//inicializa o dhtmlHistory no final do load da página 
//(caso as imagens da 1ª página demorem a carregar ao fazer back e forward pode acontecer ver-se a 1ª página antes do refresh actualizar)
window.onload = initialize;

var __searchLocationFlag = false;
var __searchLocationValue = null;

/** 
 * Inicialização - chamada quando a página acaba de ser carregada 
 **/
function initialize(flag) {
	//alert('initialize();');
	// inicialização da framework DHTML History
	dhtmlHistory.initialize();
	   
	//add ourselves as a DHTML History listener
	dhtmlHistory.addListener(handleHistoryChange);

	// subscrevemos o clique do mouse à paginação (span que tem as páginas)
	createMouseEvent();

	// determine what our initial location is by retrieving it from the browser's location after the hash
	var currentLocation = dhtmlHistory.getCurrentLocation();
			      
	// if there is no location then display the default, which is the inbox
	if (currentLocation == "") {
		currentLocation = "section:pagina_1";
	}
		
	// extract the section to display from the initial location 
	currentLocation = currentLocation.replace(/section\:/, "");
			   
	// display this initial location - caso seja a 1ª vez que é carregada não é usado o ajax (a action já devolve os resultados)
	displayLocation(currentLocation, null);
}
/** 
 * Quando estamos a navegar no Histórico (botões do Browser) 
 **/
function handleHistoryChange(newLocation, historyData) {
	//alert('handleHistoryChange('+newLocation+','+ historyData+')');
	// Se não for recebida nenhuma localização usa a default - página 1
	if (newLocation == "") {
		newLocation = "section:pagina_1";
	}
   
	// extract the section to display from the location change; newLocation will begin with the word "section:" 
	newLocation = newLocation.replace(/section\:/, "");
   
	// update the browser to respond to this DHTML history change
	displayLocation(newLocation, historyData);
}
/** 
 * Posiciona a página no ponto pretendido da pesquisa
 **/
function displayLocation(newLocation, sectionData) {
	//alert('displayLocation(' + newLocation + ','+sectionData+')');
	//recolhe a chamada a ser realizada - neste div tem a informação para a chamada ajax a página está representada pelo caracter '#'
	// que deverá ser substituido pela página pretendida antes da chamada
	var ajaxCall = $('historyAjaxLinkContruction').innerHTML;
  
	//caso haja informação faz a chamada
	if(ajaxCall != null){
		//cria um array com os elementos separados pelo token '_' - 
		var tokens = newLocation.split('_');
	   
		if(Object.isArray(tokens)){
			var pageCalled = tokens[tokens.length-1];		   
			ajaxCall = $('historyAjaxLinkContruction').innerHTML.replace('#', pageCalled);
	   }else{
		   ajaxCall = $('historyAjaxLinkContruction').innerHTML.replace('#', '1');
	   }
	}

	//teste para actualizar a hash
	//actualizaHashHistorico(newLocation,sectionData);
	
	//actualiza o formLogin ou logout dependendo do estado do login
	__searchLocationValue = newLocation;
	changeLoginFormOrigem(newLocation);
	
	try {
		if(!firstExecution){
			//alert('NEXT CALL');
			//chamada por ajax das localizações - dentro do elemento está a chamada da função javascript
			eval(ajaxCall);
		}else{
			//alert('First CALL ou F5 ou back de uma página diferente da pesquisa');
			if(pageCalled>1){
				//alert('PAGE > 1');
				eval(ajaxCall);
			}else{
				//alert('Página == 1');
				firstExecution = false;
			}
		}
	}catch(err){
		//alert('eval failled');
	}
}
/** 
 * Responde aos cliques do rato na paginação (área da paginação)
 * Não há necessidade de fazer o displayLocation porque depois de disparar o evento
 * ele chama a função de pesquisa que posiciona tudo
 **/
function handleMouseClick(e) {
   // normalizar os eventos
   var evt;
	
   if (typeof window.event != "undefined"){ // IE
      evt = window.event;
   }else{ // W3C
      evt = e;
   }
	      
   // normalizar event target
   var target;
   if (typeof evt.srcElement != "undefined"){ // IE
      target = evt.srcElement;
   }else{ // W3C
      target = evt.target;
   }

   var newLocation = target.id;
   //alert('handleMouseClick("'+target.id+'")');   
   
   //apenas os cliques nos botões são associado ao Histórico - os cliques no próprio elemento são ignorados
   if(target.id!='search_paginacao' && target.id!='search_paginacaoTop' && target.id!='search_paginacaoBottom'){
	   var modifiedLocation = "section:" + newLocation;
	   var historyData = "<p>Localização: " + modifiedLocation + "</p>";
	   
	   dhtmlHistory.add(modifiedLocation, historyData);

	   //função que chama o ajax para submeter a pesquisa e mostrar a posição correcta
	   displayLocation(newLocation, null);
   }
}


/**
 * 
 * @return
 */



function changeLoginFormOrigem(newLocation){
	//actualiza o redirect do popup do login 
	var form = null;
	var urlElement = null;
	
	//inicia o form a ser actualizado
	if(logged_in_js==null || logged_in_js){
		form = $('frmLogout');			
	}else{
		form = $('fLogin');
	}
	
	
	if(form!=null){
		//aceder ao campo onde está o url para o redirect após a chamada do login/logout
		if($('frmLogout')!=null){
			urlElement = form['urlfrom'];
		}else{
			if($('fLogin')!=null){
				urlElement = form['origem'];
			}
		}
		

		if(urlElement!=null){
			__searchLocationField = urlElement; 			
			
			//caso o url já tenha uma section actualizamos apenas após o :
			var urlTokens = $(urlElement).getValue().split(':');
			
			if(Object.isArray(urlTokens) && urlTokens.length > 1){
				//actualizamos à frente da section
				$(urlElement).setValue(urlTokens[0] + ':' + newLocation);
				__searchLocationValue = urlTokens[0] + ':' + newLocation;
			}else{
				//actualizamos todo o link
				$(urlElement).setValue($(urlElement).getValue() + '#section:' + newLocation);
				__searchLocationValue = $(urlElement).getValue() + '#section:' + newLocation;
			}
			
			__searchLocationFlag = true;
		}
	}
}


/**
 * Beta - Actualiza a hash na sessão do browser
 */
function actualizaHashHistorico(currentLocation,sectionData){
	//alert('Passo 1');
	var pagina = 1;
	var tokens = currentLocation.split('_');
	   
	if(Object.isArray(tokens) && tokens.length>1){
		pagina = tokens[tokens.length-1];
	}
	
	if (window.hashPages == undefined) {
		//alert('Passo 1.1');		
		// Store the info as a global object.
		window.hashPages = [ 
		                     [currentLocation, sectionData] 
		                   ];
		
		// cache the address book so it exists even if the user leaves the page and then returns with the back button
		historyStorage.put("hashPages", hashPages);
	} else {
		//alert('Passo 1.2');

		// fetch the cached address book from the history storage
		window.hashPages = historyStorage.get("hashPages");
		
		//cria uma nova hash com mais 1 posição
		var auxHashpage =  array(window.hashPages.length+1)

		//copia para a nova hash os elementos da antiga
		//alert('Passo 1.3');		
		for ( var i = 0; i < auxHashpage.length; i++) {
			auxHashpage[i] = window.hashPages[i]; 
		}
		
		//alert('Passo 1.4');		
		//adiciona o novo elemento
		auxHashpage[window.hashPages.length] =  [currentLocation, "Pag. " + pagina];
		window.hashPages = null;
		window.hashPages = auxHashpage; 
		
		//alert('Passo 1.5');		
		for ( var i = 0; i < window.hashPages.length; i++) {
			sectionData += "window.hashPages[" + i + "]=" + window.hashPages[i] + "/n";
		}
		//alert(sectionData);
	}
}

/** 
 * Como está dentro do ajx é necessário fazer a associação em cada chamada 
 **/
function redoMouseEvents(pagina) {
	//associa o listener novamente
	dhtmlHistory.addListener(handleHistoryChange);

	//cria os eventos de clique do rato
	createMouseEvent();
}

/**
 * Associa os eventos do rato
 **/
function createMouseEvent(){
	//depois do pedido a ajax perde os eventos associados às páginas
	var paginasTop = document.getElementById("search_paginacaoTop");
	var paginasBottom = document.getElementById("search_paginacaoBottom");

	if(paginasTop!=null && paginasBottom!=null ){
		if (typeof window.attachEvent != "undefined") {
			// Internet Explorer
			paginasTop.attachEvent("onclick", handleMouseClick);
			paginasBottom.attachEvent("onclick", handleMouseClick);
		}else { // W3C standards
		    paginasTop.addEventListener("click", handleMouseClick, false);
		    paginasBottom.addEventListener("click", handleMouseClick, false);
		}
	}
	
	
} 




