// $Id: services.js,v 1.19 2009/09/22 14:24:31 goncalves Exp $

/**
 * Open the legend tab (with at least a notice block)
 * @param serviceUrl URL of the Notice service (not used)
 * @param layerId Id of the layer associated with this service
 */
function getNotice(serviceUrl,layerId){
	var legendTabContainer = dijit.byId("legendTabContainer");
	if (legendTabContainer) {
		legendTabContainer.selectChild(dijit.byId("legendTab2"));
	}
}

/**
 * Call a Notice and a CustoLegend service
 * @param custoLegendUrl URL of the CustoLegend service (has to contain BBOX=%BBOX% parameter)
 * @param noticeUrl URL of the Notice service (has to contain BBOX=%BBOX% parameter)
 * @param resultDivName Name of the div in which the result will be displayed
 */
function getCustoLegendAndNotice(custoLegendUrl, noticeUrl, getGeometryUrl, resultDivName){
	// Build the request
	noticeUrl = noticeUrl.replace(/%BBOX%/,config.objects.mainMap.getBoundingBox());

	dojo.xhrGet(
	{
//		url : "./proxy?url=" + escape(noticeUrl),
		url : noticeUrl,
		handleAs: "json",
		load: function(responseObject, ioArgs) {
			displayNoticesLink(responseObject, custoLegendUrl, getGeometryUrl, resultDivName);
		}
	}
	);
}

/**
 * Get a Notice service result and display the notices in the legend tab
 * @param jData Result (JSON) with the notices (name and link)
 * @param custoLegendUrl URL of the CustoLegend service (has to contain BBOX=%BBOX% parameter)
 * @param resultDivName Name of the div in which the result will be displayed
 */
function displayNoticesLink(jData, custoLegendUrl, getGeometryUrl, resultDivName){
	if (jData != null) {
		var noticesList = jData.notices;
		var divNoticeLink = document.getElementById(resultDivName);
		if(divNoticeLink != null && noticesList != null && noticesList.length > 0){
			divNoticeLink.innerHTML = "<a href=\"javascript:return false;\" onclick=\"javascript:getCustoLegend('" + custoLegendUrl + "', '" + getGeometryUrl + "', '" + resultDivName + "');\" class=\"infoterreLink\">Afficher la l&eacute;gende dynamique</a><br/><br/>";
			for (i=0;i<noticesList.length;i++){
				var name = noticesList[i].nom;
				var url = noticesList[i].url;
				var lien = document.createElement("a");
				lien.setAttribute("target", "_blank");
				lien.setAttribute("href",url);
				lien.className = "infoterreLink";
				lien.innerHTML = "Notice de : " + name;
				divNoticeLink.appendChild(lien);
				var br = document.createElement("br");
				divNoticeLink.appendChild(br);
			}
		}
	}
}

/**
 * Call a CustoLegend service
 * @param custoLegendUrl URL of the CustoLegend service (has to contain BBOX=%BBOX% parameter)
 * @param resultDivName Name of the div in which the result will be displayed
 */
function getCustoLegend(custoLegendUrl, getGeometryUrl, resultDivName){
	// Build the request
	custoLegendUrl = custoLegendUrl.replace(/%BBOX%/,config.objects.mainMap.getBoundingBox());

	var divCustoLegend = document.getElementById(resultDivName);
	if(divCustoLegend != null) {
		divCustoLegend.innerHTML = "<font class=\"defaultMessage\">Construction de la l&eacute;gende en cours...</font>";

		dojo.xhrGet(
		{
//			url : "./proxy?url=" + escape(custoLegendUrl),
			url : custoLegendUrl,
			handleAs: "json",
			load: function(responseObject, ioArgs) {
				displayCustoLegend(responseObject, getGeometryUrl, resultDivName);
			}
		}
		);
	}
}

/**
 * Get a CustoLegend service result and display the legend in the legend tab
 * @param jData Result (JSON) with the legends
 * @param resultDivName Name of the div in which the result will be displayed
 */
function displayCustoLegend(jData, getGeometryUrl, resultDivName){
	if (jData != null) {
		var divCustoLegend = document.getElementById(resultDivName);
		if(divCustoLegend != null && jData != null && jData.length > 0){
			var divCustoLegendHTML = "";
			for (i=0;i<jData.length;i++){
				var feuille = jData[i];
				var carte = feuille.carte;
				var numero = feuille.numero;
				var noticeUrl = feuille.notice_url;
				var formations = feuille.formations;
				
				var arrowId = resultDivName + "_arrow_sheet_" + numero;
				var blockId = resultDivName + "_sheet_" + numero;
				divCustoLegendHTML += "<div class=\"custoLegendSheetTitle\"><img id=\"" + arrowId + "\" src=\"style/default/images/flech_noir_bas.gif\" class=\"imgLegendList\" onclick=\"showSubRowLayer('" + arrowId + "','" + blockId + "','flech_noir_bas.gif','flech_noir_dte.gif');\" />" + carte;
				if (noticeUrl != null) {
					divCustoLegendHTML += "&nbsp;(<a class=\"infoterreLink\" target=\"_blank\" href=\"" + noticeUrl + "\">Notice</a>)";
				}
				divCustoLegendHTML += "</div><div id=\"" + blockId + "\" class=\"custoLegendSheetContent\">";
				if (formations != null && formations.length > 0) {
					for(j=0;j<formations.length;j++){
						var formation = formations[j];
					    var specialText = null;
						if (getGeometryUrl != null) {
							specialText = "style=\"cursor:pointer;background-image:url(" + formation.motif + ")\" title=\"Surligner les formations correspondantes\" onclick=\"javascript: getGeometry('" + getGeometryUrl + "', '" + numero + "', '" + formation.code + "');\"";
						} else {
							specialText = "style=\"background-image:url(" + formation.motif + ")\"";
						}
						divCustoLegendHTML += "<div class=\"custoLegendMotif\" " + specialText + ">&nbsp;</div><div class=\"custoLegendDescription\">" + formation.description + "</div><br style=\"clear:both;\"/>";
					}
				}
				divCustoLegendHTML += "</div>";
			}
			divCustoLegend.innerHTML = divCustoLegendHTML;
			
			//printPage
			var divHelp = document.getElementById("helpPrintDiv");
			if (divHelp) {
				divHelp.style.display = "block";
			}
		} else {
			divCustoLegend.innerHTML = "Pas de l&eacute;gende pour cette zone";
		}
	}
}

function getGeometry(getGeometryUrl, carte, code) {
	// Build the request
	getGeometryUrl = getGeometryUrl.replace(/%BBOX%/,config.objects.mainMap.getBoundingBox());
	getGeometryUrl = getGeometryUrl.replace(/%SHEET%/,carte);
	getGeometryUrl = getGeometryUrl.replace(/%CODE%/,code);

	dojo.xhrGet(
	{
//		url : "./proxy?url=" + escape(getGeometryUrl),
		url : getGeometryUrl,
		handleAs: "json",
		load: function(responseObject, ioArgs) {
			highlightGeometry(responseObject);
		}
	}
	);
}

function highlightGeometry(jData){
	if (jData != null) {
		if(jData != null && jData.length > 0){
            var style_blue = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
            style_blue.strokeColor = "red";
            style_blue.fillOpacity = 0.3;
            style_blue.graphicOpacity = 1;
            style_blue.fillColor = "red";
            style_blue.strokeWidth = 0;
            var vectorLayer = new OpenLayers.Layer.Vector("GeometryFormation", {style: style_blue});
            config.objects.mainMap.map.addLayer(vectorLayer);
			var wktParser = new OpenLayers.Format.WKT();

			for (i=0;i<jData.length;i++){
		        if (jData[i] && jData[i].geometry && jData[i].geometry.indexOf("EMPTY") < 0) {
		        	var feature = wktParser.read(jData[i].geometry);
		        	vectorLayer.addFeatures([feature]);
			    }
			}
            setTimeout("removeGeometryFormationLayer('" + vectorLayer.id + "')",1000);
		}
	}
}

function removeGeometryFormationLayer(layerId) {
    var vectorLayer = config.objects.mainMap.map.getLayer(layerId);
    if (vectorLayer != null) {
        config.objects.mainMap.map.removeLayer(vectorLayer);
    }
}

/**
 * Call the "Download text" service to check
 * @param params A table with one row. It contains the url to the Json service
 * @param layerId Id of the layer associated with this service
 * @param label Label of the service. Use for the loading.
 */
function downloadText(params,layerId,label) {
	var adresse = params[0];
	var bbox = config.objects.mainMap.getBoundingBox();
	var Xmin = bbox[0];
	var Ymin = bbox[1];
	var Xmax = bbox[2];
	var Ymax = bbox[3];
	var SRS = config.objects.mainMap.getSRS();
	adresse = adresse.replace(/%XMIN%/,Xmin);
	adresse = adresse.replace(/%YMIN%/,Ymin);
	adresse = adresse.replace(/%XMAX%/,Xmax);
	adresse = adresse.replace(/%YMAX%/,Ymax);
	adresse = adresse.replace(/%SRS%/,SRS);
	adresse += "&Check=true";

	var dijitLoader = dijit.byId("LoadingToaster");
	var mId = dijitLoader.addMessage(label + getLayerTitle(layerId));

	dojo.xhrGet(
	{
//		url : "./proxy?url=" + escape(adresse),
		url : adresse,
		handleAs: "json",
		load: function(responseObject, ioArgs) {
			checkTestDLText(responseObject);
			dijitLoader.removeMessage(mId);
		},
		error: function(err) {
			displayErrorMessage(gErrors["error.service.global"]);
			dijitLoader.removeMessage(mId);
    	}
	}
	);
	
}

/**
 * Check and Make if positif for the download Text
 * @param JResponse JSon response from the service "Download text"
 */
function checkTestDLText(JResponse) {
	if (JResponse.itIsOk) {
		window.location.href=JResponse.dlUrl;
	} else {
		displayErrorMessage(gErrors["error.service.tooMany"]);
	}
	
}

/**
 * Call the "Download data" service
 * @param params A table with three row. First is the service URL, second is the wfsURL and third is the format.
 * @param layerId Id of the layer associated with this service
 * @param label Label of the service. Use for the loading.
 */
function downloadData(params,layerId,label) {
	// Get the parameters
	var serviceUrl = params[0];
	var wfsUrl = params[1];
	var format = params[2];

	var dijitLoader = dijit.byId("LoadingToaster");
	var mId = dijitLoader.addMessage(label + "(" + getLayerTitle(layerId) + ")");
	
	// Get the bounding box
	var currentSRS = config.objects.mainMap.getSRS();
	var currentProj = new Proj4js.Proj(currentSRS);
	var bbox = config.objects.mainMap.getBoundingBox();
	var ul ={x:bbox[0],y:bbox[3]};
	var lr={x:bbox[2],y:bbox[1]};
	if(currentProj.srsCode.toUpperCase()!="EPSG:4326"){
		var epsg4326 = new Proj4js.Proj("EPSG:4326");
		Proj4js.transform(currentProj,epsg4326,ul);
		Proj4js.transform(currentProj,epsg4326,lr);	
	}

	// Rebuild the url
	serviceUrl = serviceUrl.replace(/%XMIN%/,ul.x);
	serviceUrl = serviceUrl.replace(/%YMIN%/,lr.y);
	serviceUrl = serviceUrl.replace(/%XMAX%/,lr.x);
	serviceUrl = serviceUrl.replace(/%YMAX%/,ul.y);
	serviceUrl = serviceUrl.replace(/%URL%/, encodeURIComponent(wfsUrl));
	serviceUrl = serviceUrl.replace(/%FORMAT%/,format);
	window.location.href=serviceUrl;
	dijitLoader.removeMessage(mId);
}

/**
 * Open the "OpenSearchLayer" dialog box
 * @param params A table with two rows. First contains the url to the Json service, the second is the layer name.
 * @param layerId Id of the layer associated with this service
 * @param label Label of the service. Use for the loading.
 */
function openSearchLayer(params,layerId,label) {
	var url = params[0];
	
	var searchDialog = dijit.byId('SearchLayerDialogBox');
	
	if (searchDialog.isLoaded) {
		document.getElementById('searchLayerURL').value = url;
		document.getElementById('searchLayerId').value = layerId;
		document.getElementById('searchLayerLoadingMessage').value = label;
	} else {
		dojo.connect(searchDialog,"onLoad",function() {
			document.getElementById('searchLayerURL').value = url;
			document.getElementById('searchLayerId').value = layerId;
			document.getElementById('searchLayerLoadingMessage').value = label;
		});
	}
	
	
	searchDialog.show();
}

function openLegend(params,layerId,label) {
	var serviceUrl = params[0];
	
	serviceUrl = serviceUrl.replace(/%SRS%/,config.objects.mainMap.getSRS());
	serviceUrl = serviceUrl.replace(/%BBOX%/,config.objects.mainMap.getBoundingBox());
	serviceUrl = serviceUrl.replace(/%TITLE%/,label);

	window.open(serviceUrl);
	
}

/**
 * Get the Title of the Layer
 */
function getLayerTitle(layerId) {
	var layer = config.objects.mainMap.getLayer(layerId);
	if (layer) {
		var title = layer.selectSingleNode("wmc:Title").firstChild.nodeValue;
		return " (" + title + ")";
	} else
		return "";
}	