// =============================================================
//
// Copyright (c) 2000-2004 General Electric Company. 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;
var entorno_sim='catastro_sias';

//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 loginReq;
var mapWidth;
var mapHeight;

// ---------  Start / Stop HCF ------------------
function start(entorno,idioma,dia) {
 
 var d =dia.toUpperCase();
      login(entorno,idioma,d );
  
}

function login(entorno,idioma,dia) {
   /* This method logs a user into a SIAS session.
      
      Parameters: none
      Return: none
   */ 
  
   loginReq = false;
   temas = "VACIO";
	if (temas != null && temas != '') {
	temas = "VACIO,"+temas;
	}
	else {
	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;
		default:
		 	L=0;
			break;
		}
	
	var frame_menu='';
	
   // 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 == "") {
   if (loginReq) {
      
      // 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);
   top.registerContentListener('urbanismoweb', hcfRoot.updateThemesPanel, top.hcf_panel);
   top.registerContentListener('catastroweb', hcfRoot.updateThemesPanel, top.hcf_panel);
   //top.registerContentListener('map_catastro', top.updateNavPanel, top.hcf_panel);
	// top.registerContentListener('map_urbanismo', top.updateNavPanel, top.hcf_panel);
    


   // Get default Map 
   // create a new message
   var aMessage = new hcfRoot.Message();

   // set up target
   aMessage._target.frame = hcfRoot.hcf_content;

   // Use default bookmark as configured in globals.js
   aMessage.registerUrlParam('swldy_view', hcfRoot.DEFAULT_VIEW);

   // Use default world as configured in globals.js
   aMessage.registerUrlParam('swldy_world', hcfRoot.DEFAULT_WORLD);
	
   // Use default ACE as configured in globals.js
   aMessage.registerUrlParam('swldy_ace', hcfRoot.DEFAULT_ACE);
   
    // Use default drawing application as configured in globals.js
   aMessage.registerUrlParam('swldy_drapp', hcfRoot.DEFAULT_DRAPP);
   
   // usamos el sistema de coordenadas
   aMessage.registerUrlParam('srs', 'GENS:utm_29');


	
   // Map size
   mapWidth = getCurrentWinWidth(top.hcf_content) - MAP_WIDTH_OFFSET;
   mapHeight = getCurrentWinHeight(top.hcf_content) - MAP_HEIGHT_OFFSET;
   aMessage.registerUrlParam('width', mapWidth);
   aMessage.registerUrlParam('height', mapHeight);


	//Entorno
	if (entorno == null){
   		var entornoElement = aBatchForm.swldy_ace;
	   if (entornoElement != null) {
			var entorno=entornoElement.value;
		   }
   			else {
   				entorno = 'callejero_sias';
			}
	}


entorno_sim = entorno;
    
   // now register layers parameter   
   // REMOVED: Most browsers limit the size of a request on the URL. Since Layers
   // tend to involve quite a large request we dynamically add a field to the batch form
   // in order to submit the request.
   //hcfRoot.registerParam('layers', result);

  var layers ='';
 hcfRoot.diaSanto = null;
		
		switch (entorno) {
		
	      	case 'catastro_sias':
			aMessage.registerUrlParam('swldy_ace', 'catastroweb_sias');
			aMessage.registerUrlParam('swldy_drapp', 'Default');
			aMessage.registerUrlParam('swldy_themes', '2administrativo,2catastro_urbano,2parcelario_aparente,2mobiliario,2raster,vacio');
			
			//layers= "swrefVthemeVace_idZ833131VnameZAdministrativo,swrefVthemeVace_idZ833131VnameZCartografia,swrefVthemeVace_idZ833131VnameZRaster";
			//,Parcelario Aparente,Mobiliario,Raster 1:10.000,Estado');
			break;
		case 'catastroweb_sias':
			aMessage.registerUrlParam('swldy_ace', 'catastroweb_sias');
			aMessage.registerUrlParam('swldy_drapp', 'Default');
			aMessage.registerUrlParam('swldy_themes', '2administrativo,2catastro_urbano,2parcelario_aparente,2mobiliario,2raster,vacio');
			
			//layers= "swrefVthemeVace_idZ833131VnameZAdministrativo,swrefVthemeVace_idZ833131VnameZCartografia,swrefVthemeVace_idZ833131VnameZRaster";
			//,Parcelario Aparente,Mobiliario,Raster 1:10.000,Estado');
			break;
		case 'urbanismoweb_sias':
			aMessage.registerUrlParam('swldy_ace', 'urbanismoweb_sias');
			aMessage.registerUrlParam('swldy_drapp', 'urbanismo');
			aMessage.registerUrlParam('swldy_themes', '0defecto,2cartografia,2raster,vacio');
			break;
		case 'urbanismo_sias':
			aMessage.registerUrlParam('swldy_ace', 'urbanismoweb_sias');
			aMessage.registerUrlParam('swldy_drapp', 'urbanismo');
			aMessage.registerUrlParam('swldy_themes', '0defecto,2cartografia,2raster,vacio');
			break;
		case 'callejero_sias':
			 	aMessage.registerUrlParam('swldy_ace', 'callejero_sias');
			  	aMessage.registerUrlParam('swldy_drapp', 'callejero');
			   	aMessage.registerUrlParam('swldy_themes', '0transporte,0alojamiento,2callejero,2portales,2raster,vacio');
		
				frame_menu='';
			break;
		case 'semana_santa':
			 	aMessage.registerUrlParam('swldy_ace', 'callejero_sias');
			  	aMessage.registerUrlParam('swldy_drapp', 'callejero');
			   	aMessage.registerUrlParam('swldy_themes', '0transporte,0alojamiento,2callejero,2portales,2raster,vacio');
				frame_menu='';
				var tema = '2callejero,,monumentos_civiles,monumentos_religiosos,museos,parques,administracion_local,centro_salud,hospital,';		
				hcfRoot.diaSanto=dia;
			
				if (dia != "")
					{
						// obtengo el tema
					tema =tema + '3'+dia.toLowerCase().replace(' ','_').replace(' ','_'); 
					hcfRoot.registerParam('swldy_themes',tema);
				}
			//	hcfRoot.loadPage(top.hcf_panel, 'SEMANA SANTA', 'panel_semana_santa.xsl');
			// Remove listeners for active panel here
   hcfRoot.unregisterContentListener(hcfRoot.hcf_panel);
   hcfRoot.unregisterContentListener(hcfRoot.hcf_content);
			break;
	}
	
   // setup request    
   aRequest = aMessage.registerRequest();
   aRequest.name = 'map';
   aRequest.format = 'xml';

   // setup transform
   aTransform = aMessage.registerTransform();
   aTransform.stylesheet = 'content_map.xsl';

   // submit the request
   hcfRoot.aSubmitHandler.doMessage(aMessage);
  
    //top.header.window.location.href = 'frames_header' + frame_menu + '.html';
    //top.header.window.location.href = 'frames_header' + '.html';
   
  
   if (entorno=='semana_santa')
   	hcfRoot.loadPage(top.hcf_panel, 'SEMANA SANTA', 'panel_semana_santa.xsl');
   
}   


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;
	}

	// Here we check if the user has passed in a name for a PopUp window.
	// If they have, we spawn a new window and make the target of the request
	// that window.
	//if (aPopUpName) {
	//	openDialog('../start.html', aPopUpWidth, aPopUpHeight, '', aPopUpName);
	//	aBatchForm.target = aPopUpName;
	//if (aProgressIndicator)
	//		aProgressIndicator.style.visibility = 'hidden';
	//}

   // 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;
}

