function Controller() {
}

Controller._componentWindowRefs = new Array();

Controller._getComponentWindow = function(windowName) {
	if ((windowName != null) && (windowName != '')) {
		var _windowRef = Controller._componentWindowRefs[windowName];
		if ((_windowRef != null) && (_windowRef != undefined)) {
			return _windowRef;
		} else {
			return null;
		}
	} else {
		return null;
	}
}

Controller._addComponentWindow = function(windowName, windowRef) {
	if ((windowName != null) && (windowName != '') && (windowRef != null) && (windowRef != undefined)) {
		Controller._componentWindowRefs[windowName] = windowRef;
	}
}

Controller._deleteComponentWindow = function(windowName) {
	if ((windowName != null) && (windowName != '') && (Controller._componentWindowRefs[windowName])) {
		Controller._componentWindowRefs[windowName] = null;
	}
}

Controller._isValidWindow = function(windowRef, URL, windowName, framePath) {
	return ((windowRef != null)
		&& (windowRef != undefined)
		&& (! windowRef.closed)
		&& (windowRef.name == windowName)
		&& ((windowRef.location.href == URL)
			|| ((framePath) && (eval("windowRef." + framePath + ".location.href").indexOf(URL) == 0))));
}

Controller._openComponent = function(URL, windowName, framePath, windowOpts, defaultOpts, userParams, referer) {
	var url = URL;
	var queryArray = new Array();
	var queryString = "";
	if ((referer != null) && (referer != '')) {
		queryArray.push("referer=" + referer);
	}
	if ((defaultOpts != null) && (defaultOpts != '')) {
		queryArray.push(defaultOpts);
	}
	if ((userParams != null) && (userParams != '')) {
		queryArray.push(userParams);
	}
	if (queryArray.length > 0) {
		queryString = queryArray.join("&");
		url = url + "?" + queryString;
	}

	// abrir la ventana donde cargar el componente
	var windowRef = null;
	if ((windowName != null) && (windowName != '')) {
		// primero comprobamos si ya la tenemos abierta
		windowRef = Controller._getComponentWindow(windowName);
		
		// si no es una referencia valida, tendremos que abrir ventana nueva
		if (! Controller._isValidWindow(windowRef, URL, windowName, framePath)) {
			windowRef = window.open('', windowName, windowOpts);
			
			// comprobar que se ha obtenido una referencia a ventana valida
			// puede haber sido bloqueada por el navegardor pensando que era un popup
			if ((windowRef != null) && (windowRef != undefined)) {
				
				// guardar la nueva referencia
				Controller._addComponentWindow(windowName, windowRef);
			} else {
				
				// eliminar la entrada de la cache de ventanas
				Controller._deleteComponentWindow(windowName);
				alert("No se pudo cargar el componente. Por favor, vuelva a intentarlo.");
			}
		}
	} else {
		windowRef = window.open('', windowName, windowOpts);
	}

	// comprobar si se debe cargar en un frame
	// concreto de la ventana
	if ((framePath != null) && (framePath != "")) {
		
		var ruta = "windowRef." + framePath;
		windowRef = eval(ruta);
	}

	var _location = windowRef.location.href;
	if(_location.indexOf(url) != 0)
	{
		// La aplicación no está cargada
		windowRef.location = url;
	}
	return windowRef;
}

Controller.openAnonymousComponent = function(componentType, userParams, referer) {
	return Controller._openComponent(Controller.direcciones[componentType],	// URL
	 			'',	// windowName
	 			'',	// framePath 
	 			Controller.opcionesVentana[componentType],	// windowOpts
	 			Controller.opcionesAplicacion[componentType],	// defaultOpts
	 			userParams,
	 			referer);
}

Controller.openUniqueComponent = function(componentType, userParams, referer) {
	return Controller._openComponent(Controller.direcciones[componentType],	// URL
	 			Controller.ventanas[componentType],	// windowName
	 			'',	// framePath 
	 			Controller.opcionesVentana[componentType],	// windowOpts
	 			Controller.opcionesAplicacion[componentType],	// defaultOpts
	 			userParams,
	 			referer);
}

Controller.openNamedComponent = function(componentType, windowName, framePath, userParams, referer) {
	return Controller._openComponent(Controller.direcciones[componentType],	// URL
	 			windowName,
	 			framePath, 
	 			Controller.opcionesVentana[componentType],	// windowOpts
	 			Controller.opcionesAplicacion[componentType],	// defaultOpts
	 			userParams,
	 			referer);
}

/**
 * Obtener la interfaz de la aplicación applicationName para acceder a sus servicios.
 * Función interna. Intenta abrir la ventana de la aplicación y cargarla
 * para obtener una instancia de su interfaz de servicios.
 * @param componentType tipo del componente del que obtener el
 * 	proxy {_VISUALIZADOR, _NOMENCLATOR, _WMS_CONFIGURABLE_CLIENT}
 * @param proxyRef nombre de la var donde dejar el proxy (necesaria para poder
 *	acceder al proxy recuperado cuando la función se ejecuta de forma
 *	asíncrona - no devuelve el proxy inmediatamente, si no dentro de
 *	un tiempo)
 * @param numberOfRetries numero de intentos consumidos en cargar la aplicación.
 */

Controller._getComponentProxy = function(URL, windowName, framePath, windowOpts, defaultOpts, userParams, proxyRef, numberOfRetries) {
	var windowRef = Controller._openComponent(URL, windowName, framePath, windowOpts, defaultOpts, userParams, '');
	if (numberOfRetries < Controller.MAX_N_OF_RETRIES) {
		numberOfRetries++;
		// Condición de fallo
		if ((windowRef.isLoaded == null) // Seguirá habiendo isLoaded en las ventanas??
		   || (! windowRef.isLoaded)) {
			// Programamos el tiempo de espera para que se cargue
			// la ventana de la aplicación
			timeout = numberOfRetries * Controller.TIMEOUT_BASE;
			setTimeout("Controller._getComponentProxy(" 
					+ "'" + URL + "', " 
					+ "'" + windowName + "', " 
					+ "'" + framePath + "', "
					+ "'" + windowOpts + "', "
					+ "'" + defaultOpts + "', "
					+ "'" + userParams + "', "
					+ "'" + proxyRef + "', "
					+ numberOfRetries
					+ ")",
			           timeout);
		} else {
			// Se cargo el cliente
			// Obtener la instancia del proxy y devolverla
			var _appProxy = new ComponentProxy(windowRef);
			// Guardo copia del proxy en la referencia que me pasan
			eval(proxyRef + " = _appProxy");
			return _appProxy;
		}
	} else {
		return null;
	}
}

Controller.getAnonymousComponentProxy = function(componentType, userParams, proxyRef) {
	return Controller._getComponentProxy(Controller.direcciones[componentType],	// URL
	 			'',	// windowName
	 			'',	// framePath 
	 			Controller.opcionesVentana[componentType],	// windowOpts
	 			Controller.opcionesAplicacion[componentType],	// defaultOpts
	 			userParams,
	 			proxyRef,
	 			0);	// numberOfRetries
}

Controller.getUniqueComponentProxy = function(componentType, userParams, proxyRef) {
	return Controller._getComponentProxy(Controller.direcciones[componentType],	// URL
	 			Controller.ventanas[componentType],	// windowName
	 			'',	// framePath 
	 			Controller.opcionesVentana[componentType],	// windowOpts
	 			Controller.opcionesAplicacion[componentType],	// defaultOpts
	 			userParams,
	 			proxyRef,
	 			0);	// numberOfRetries
}

Controller.getNamedComponentProxy = function(componentType, windowName, framePath, userParams, proxyRef) {
	return Controller._getComponentProxy(Controller.direcciones[componentType],	// URL
	 			windowName,
	 			framePath, 
	 			Controller.opcionesVentana[componentType],	// windowOpts
	 			Controller.opcionesAplicacion[componentType],	// defaultOpts
	 			userParams,
	 			proxyRef,
	 			0);	// numberOfRetries
}


