// =============================================================
//
// Copyright (c) 2000-2003 GE Smallworld. All Rights Reserved.
//
// =============================================================

//this builds an array for all service parameters that will be added
//to the batch_form action  
//the first field of the array is the param name 
//and the second field is the param  value

var hcfRoot = this.top;

var registeredParams = new Array(MAX_PARAMS);
for (x=0;x<MAX_PARAMS;x++) {

	registeredParams[x] = new Array(2);
}

var PARAM_COUNT = 0;

//this builds an array for all client state requests that will be added
//to the batch_form action  
//the first field of the array is the client_state variable name 
//and the second field is the variable  value
var MAX_CLIENT_STATE_REQUESTS = 10;
var registeredClientStateRequests = new Array(MAX_CLIENT_STATE_REQUESTS);
for (x=0;x<MAX_CLIENT_STATE_REQUESTS;x++) 
	registeredClientStateRequests[x] = new Array(2);

var clientStateRequestCount=0;

// Create submitHandler object
var aSubmitHandler = new SubmitHandler();


//var L=0;  // indica el idioma: 0-Es, 1-En, 2-De, 3-Fr, 4-It


// ---------  Start / Stop HCF ------------------
function start_pt(codigo_pt,temas,idioma) {
  	// carga la aplicación ubicando el mapa en el punto de interes
  	// con código codigo_pt
  	//
  	
      // now login
    
        login_pt(codigo_pt,temas,idioma);
   }


function login_pt(codigo_pt,temas,idioma) {
   /* This method logs a user into a SIAS session.
      
      Parameters: non

      Return: none
   */ 
    //temas = "RUTA DEL VINO Y EL BRANDY";

   
   if (temas != null && temas != '') {
	//temas = "vacio,"+temas;
	temas = "estado,"+temas;
	}
else {
	temas = "Estado";
	//temas = "VACIO";
	//temas = "1JEREZ MONUMENTAL,HOTEL 5*,HOTEL 4*,HOTEL 3*,HOTEL 2*,HOTEL 1*,VACIO";
	}

	// ajustamos el idioma porque ahora php no adminte en_GB y smallworld no admite en_US
	
	var idioma_nv = 'es_ES';
	var idioma_sw = 'es_ES';
	if (idioma == null || idioma == '') {
		idioma = 'es';
	}
	
   switch (idioma) {
	      case 'es':
			  idioma_nv = 'es_ES';
			  idioma_sw = 'es_ES';
			   L=0;
			  break;
		case 'en':
			  idioma_nv = 'en_US';
			  idioma_sw = 'en_GB';
			   L=1;
			break;
		case 'de':
			  idioma_nv = 'de_DE';
			  idioma_sw = 'de_DE';
			   L=2;
			break;
		case 'fr':
			  idioma_nv = 'fr_FR';
			  idioma_sw = 'fr_FR';
			   L=3;
			break;
		case 'it':
			  idioma_nv = 'it_IT';
			  idioma_sw = 'it_IT';
			  L=4;
			break;
		default:
		 	L=0;
			break;
		}
		

   // get the batch form on hcf_content
   var aBatchForm = getBatchForm(top.hcf_content);

   // The first thing we check to see if the action on
   // hcf_content is unset.  If so then we need to
   // set it up.  The case in which it could be unset
   // is if login.html has been loaded into the
   // content_frame at HCF startup.
   if (aBatchForm.action == "") {
      
      // get the batch from the hcf_panel
      var aPanelBatchForm = getBatchForm(top.hcf_panel);
   
      // setup the action
      aBatchForm.action = aPanelBatchForm.action;
   }      

   // get user name element
   var aUserNameElement = aBatchForm.user_name;

   if (aUserNameElement != null &&
       aUserNameElement.value == '') {
		alert(USER_NAME_MESSAGE);
		return;	
	}

   // setup default listener - this will cause the
   // navigation panel to load once the map has loaded
   top.registerContentListener('map', top.updateNavPanel, top.hcf_panel);
   
   // get the map width
   mapWidth = getCurrentWinWidth(top.hcf_content) - MAP_WIDTH_OFFSET;
   mapHeight = getCurrentWinHeight(top.hcf_content) - MAP_HEIGHT_OFFSET;
   
   registerParam('width', mapWidth);
	registerParam('height', mapHeight);
	registerParam('swldy_image_format', 'png');

// cogemos el entorno

// 'turismo_sias':

	registerParam('swldy_ace', 'turismo_sias');
	registerParam('swldy_drapp', 'turismo');
	registerParam('swldy_view', hcfRoot.DEFAULT_VIEW);
	 // Use default bookmark as configured in globals.js
   	registerParam('swldy_view', hcfRoot.DEFAULT_VIEW);
	// Use default world as configured in globals.js
   	registerParam('swldy_world', hcfRoot.DEFAULT_WORLD);
	// Use default ACE as configured in globals.js
   	registerParam('swldy_ace', hcfRoot.DEFAULT_ACE);

	registerParam('swldy_themes', temas); //1MONUMENTAL,1CABALLOS,1MUSEOS Y TEMATICOS,1ALOJAMIENTOS,1OTROS SERVICIOS,1RUTA PANORAMICA');
	//register parameter
	//registerParam('srs', 'GENS:utm_29_m');
		
	// registramos el parámetro del idioma

	
	aRequest =  '<request>'+
					'<name>client_state</name>'+
					'<command>add</command>'+
					'<client_state><state><idioma>'+idioma_sw+'</idioma></state></client_state>' +
					'</request>'
					
					
	// realizamos la query con el codigo dado
	
	if (codigo_pt != null && codigo_pt != "") {
           //var query = "select id,posicion from punto_interes where id= "+codigo_pt;
           //var query = "punto_interes where id= "+codigo_pt;
	var query = "select * from punto_interes where id= "+codigo_pt;
            var aRequest = aRequest +'<request>' + 
				//'<name>browser</name>'+
				'<name>query</name>'+
				'<query>'+query+'</query>'+
				'<dataset>puntos_interes</dataset>' + 
				'<format>xml</format>'+
				'<swldy_generate_map> true </swldy_generate_map>'+
				'<swldy_zoom> true</swldy_zoom>'+
			'</request>';	
		}
	else
		{
	   // set up request
   	var aRequest = aRequest +'<request>' + 
        	             '<name>map</name>' + 
						//'<srs>GENS:utm_29_m</srs>'+
						//'<swldy_themes>'+temas+'</swldy_themes>'+
                	     '<format>xml</format>' + 
                  	'</request>';	
                  	}
                
               
   // set up stylesheet                  
   var aStyleSheet = 'content_map.xsl';

   executeRequest(top.hcf_content, aRequest, aStyleSheet);

   //Cambio frame superior
   // if (frame_menu != '')
 //top.header.window.location.href = document.location.pathname + 'frames_header' + frame_menu + '.html';

	 top.header.window.location.href = document.location.pathname + 'frames_header_turismo.php?idioma=' + idioma_nv;

}   


function logout() {
   /* This method logs a user out of a SIAS session.
      
      Parameters: none

      Return: none
   */ 
   
   // reset the panel title
   top.header.writePanelTitle('');
   
   // get the batch form on hcf_content
   var aBatchForm = getBatchForm(top.hcf_content);

   // now get the action
   var action = aBatchForm.action;
   
   // load the blank html page into hcf_panel
   top.hcf_panel.window.location.href = "start.html";

   // now set up the request
	var aRequest = '<request>' + 
                     '<name>logout</name>' + 
                  '</request>';
                  
   // set up stylesheet
   var aStyleSheet = 'panel_logout.xsl';                  

   // execute the request - this will go to the content frame
   executeRequest(top.hcf_content, aRequest, aStyleSheet);
   
}


//------------  Request Handling -----------------
function executeRequest(aFrame, aRequestString, aStylesheet, aPopUpName, aPopUpWidth, aPopUpHeight, aAnchor) {
   //	----------------------------------------------------------------------
   //	ExecuteReuest is the function that performs the final call to the server 
   //	by populating and submitting the batch form with the built up request. It
   //	also registers any parameters in the param array and adds any client state
   //	requests to the main request.
   //	Parameters:
   //		aFrame: Target frame object where request is to be performed. Must 
   //			contain	a BatchForm in order for the function to execute.
   //		aRequestString: an XML request with one or more SIAS services, each contained 
   //				within a <request></request> block.
   //		aStylesheet: in order to override the current stylesheet in the frame 
   //					a stylesheet file must be provided. If none is present the 
   //					current stylesheet in aFrame will be used.
   //		aPopUpName (optional): Name of target window to be spawned as a pop-up 
   //		aPopUpWidth (optional): Width (in pixels) of the resulting window
   //		aPopUpHeight (optional): Height (in pixels of the resulting window
   //		aAnchor (optional): Anchor tag to be inserted at the end of the action 
   //	----------------------------------------------------------------------

   // create a request object

   aRequest = new Request_deprecated();
   
   // add in the request
  
   aRequest.registerRequest(aRequestString);
   
   // set up stylesheet if its not undefined.  It will be 
   // undefined if a user did not pass in a value to
   // this function

   if (aStylesheet != undefined) {
      aRequest.stylesheet = aStylesheet;
   } 
 
   // set up target
   aRequest.target.frame = aFrame;
   
   // set up window
   if (aPopUpName != null) {
   	aRequest.target.windowName = aPopUpName;
   	aRequest.target.windowWidth = aPopUpWidth;
   	aRequest.target.windowHeight = aPopUpHeight;
   	aRequest.target.openWindow = true;
   }
   else aRequest.target.frame = aFrame;

   // setup parameters
	for (var i=0;i<PARAM_COUNT;i++) {
      aRequest.registerParameter(registeredParams[i][0],
                            	   registeredParams[i][1]);
	}

   // clear out params once we've used them
   PARAM_COUNT = 0;

   // now call do request

   this.doRequest(aRequest);

}
   
function doRequest(aRequest) {

   // get the frame
   aFrame = aRequest.target.frame;
	
   // get a batch form
	aBatchForm = getBatchForm(aFrame);
   
   // set up batch from target
   //aBatchForm.target = aFrame.name;
   
	// if the target frame is not hcf_content then populate the target frame
	// batch form from the content frame. 
	// Also check if the session_id of hcf_content is set, if it isn't then 
	// abort the execute request. This means that the user has not logged in 
	// and we do not want them to load anything into the panel frames until 
	// a valid session has been established.
	if (!populateBatchFormData(aFrame)) {
		alert(NO_SESSION_ID_MESSAGE);
		return;
	}


   // now setup indicator
   aProgressIndicatorLayer = xbGetElementById('progressIndicator', aFrame.window);
   if (aProgressIndicatorLayer != undefined) {
      // get style
      aProgressIndicatorLayerStyle = new xbStyle(aProgressIndicatorLayer);
      
      // set visiblity
      aProgressIndicatorLayerStyle.setVisibility('visible');
   }      

   // now execute the request

   aRequest.execute(aBatchForm);

   // restore any batch form values if the target of the submit 
   // was not the current window (pop-up)
//   if (aPopUpName) {
	//	aBatchForm.elements.transform.value = aPreviousTransform;
//   }
   	
   // note that we have executed a request
   requestExecuted = true;	

}

function onContentLoaded(aContentType) {
//	----------------------------------------------------------------------
//	Check content listeners for requests that match the updated content and 
//	execute the cooresponding function, then remove the listener
//	Parameters:
//		aContentType: content type id that has just been loaded
//	----------------------------------------------------------------------
	var aListener;

	for (var i=0; i < LISTENER_COUNT; i++) {
		// get request object
		aListener = contentListeners[i];


		if (aListener.contentType == aContentType) 
		{
			// execute the listener function
         if (top.navigator.family == 'ie4') {
         	
				aListener.functionRef(aListener.targetPanel);
			}
			else {
				eval(aListener.functionRef(aListener.targetPanel));
			}
		}
	}
	CURRENT_CONTENT = aContentType;

	//header.setActiveFolder(aContentType);
}

function onPanelLoaded(aPanel) {
   //	----------------------------------------------------------------------
   //	Run on all panels in the onload action that update state.
   //	Parameters:
   //		aPanel: panel that has loaded which contains updated state information
   //	----------------------------------------------------------------------

	// Now update the response object on the content page 
   	// based on the data just returned from the server.
	// Note that we need to make sure that top.hcf_content.response
 	// is defined - when a user does a refresh (without holding
        // down the ctrl key) in IE this object will be undefined.

	if (aPanel.response != null &&
            top.hcf_content.response) {
      	   // update the response object on the content frame
           top.hcf_content.response.update(aPanel.response);
	}

   // note that we need to make sure that this
   // method exists!!  When opening new windows
   // in IE it won't because map.js is loaded after
   // after frames.js.  Also note that we need to make 
   // sure that top.hcf_content.response is defined -
   // when a user does a refresh (without holding
   // down the ctrl key) in IE this object will be undefined.

	if (top.hcf_content.response &&
           top.hcf_content.response.map != null &&
           top.hcf_content.updateMapDisplay != null) {
	   top.hcf_content.updateMapDisplay();
	}
}

function populateBatchFormData(aTargetFrame) {
//	----------------------------------------------------------------------
//	Helper function that copies the state and session id from the content frame
//	to the target panel frame. This is needed to keep state the same across all 
//	frames.
//	Parameters:
//		aFrame: target frame for the batch form data to be copied
//	----------------------------------------------------------------------
	// get the master (content) batch form
	//aSourceBatchForm = getForm(aSourceFrame, '', 'BatchForm');

	// get the target panel batch form
	aTargetBatchForm = getForm(aTargetFrame, '', 'BatchForm');

	// Check to see if we have a session ID, if not then don't populate the target form
	if (aTargetBatchForm != null &&
       	aTargetBatchForm.session_id != null) {
		// set session id
		aTargetBatchForm.session_id.value = GLOBAL_CONTEXT.sessionID;
		   
		// set state dataset
		aTargetBatchForm.state_dataset.value = GLOBAL_CONTEXT.state;
		return true;
	}
	else {
		return false;
	}
}

// -------------  Register Parameters  ----------------------
function registerParam(aParamName, aParamValue) {
	if (PARAM_COUNT + 1 == MAX_PARAMS) {
		alert('SIAS HTML Client:\nMaximum parameters (' + MAX_PARAMS + ') reached.\n'+
			'Request <' + aParamName + '> could not be registered.');
		return;
	}
	
	for (var i=0;i < PARAM_COUNT;i++) {
		if(registeredParams[i][0] == aParamName) {
			registeredParams[i][1] = aParamValue;
			return;
		}
	}
	registeredParams[PARAM_COUNT][0] = aParamName;
   //aParamValue = aParamValue.replace(' ','%20');
	registeredParams[PARAM_COUNT][1] = aParamValue;
	PARAM_COUNT++;
}


// -------------  Register Response Parameters  ----------------------
function registerResponse(aParamObject, aParamName) {
	if (RESPONSE_COUNT + 1 == MAX_RESP_PARAMS) {
		alert('SIAS HTML Client:\nMaximum parameters (' + MAX_RESP_PARAMS + ') reached.\n'+
			'Request <' + aParamName + '> could not be registered.');
		return;
	}
	
	for (var i=0;i < RESPONSE_COUNT;i++) {
		if(responseParams[i][0] == aParamObject) {
			responseParams[i][1] = aParamName;
			return;
		}
	}
	responseParams[RESPONSE_COUNT][0] = aParamObject;
	responseParams[RESPONSE_COUNT][1] = aParamName;
	
	RESPONSE_COUNT ++;
}

function registerClientStateRequest(varName, varValue) {

	if (clientStateRequestCount + 1 == MAX_CLIENT_STATE_REQUESTS) {
		alert('SIAS HTML Client:\nMaximum requests (' + max_requests + ') reached.\n'+
			'Request <' + aRequest + '> could not be registered.');
		return;
	}
	
	var index = -1;
	
	// check to see if this service is already registered.  If so then 
	// overite it.  We can't have the same service registered twice 
	// because that causes an error on the server
	for (var i=0; i < clientStateRequestCount; i++) {
		if (registeredClientStateRequests[i][0] == varName) {
			index = i;
			//stop the loop
			break;
		}
	}

	if (index==-1) {
		// by default the index of this request will be equal to the
		// current request count
		index = clientStateRequestCount;
		//increment request count since this is a new request
		clientStateRequestCount ++;
	}
	
	// now save request	
	registeredClientStateRequests[index][0] = varName;
	registeredClientStateRequests[index][1] = varValue;
}	

function getClientStateRequests() {
	var clientRequest = '<request><name>client_state</name>';
	clientRequest += '<format>xml</format>';
	clientRequest += '<command>add</command>';
	clientRequest += '<client_state><client_state>';
	for (var i = 0;i < clientStateRequestCount;i++)  {
		clientRequest += '<' + registeredClientStateRequests[i][0] + '>';
		clientRequest += registeredClientStateRequests[i][1];
		clientRequest += '</' + registeredClientStateRequests[i][0] + '>';
	}
	clientRequest += '</client_state></client_state></request>';
		
	return clientRequest;
}


