// $Id: display.js,v 1.48 2009/10/28 13:02:44 goncalves Exp $

// Catalog nomenclature
var INFOTERRE_CATALOG_VIEW = "infoterre";
var INSPIRE_CATALOG_VIEW = "inspire";
var PRODUCER_CATALOG_VIEW = "producteur";

/**
 * Display the error message in the toaster.
 */
function displayErrorMessage(message) {
	dojo.publish("ErrorMessageTopic",
		[{
			message: message,
			type: "fatal",
			duration: 4000
		}]);
}

/**
 * Triggered when the mainMapPane is resized
 */
function onMapResizeHandler() {
    if (config.objects.mainMapWidget) {
        config.objects.mainMapWidget.resize(config.objects.mainMapWidget);     
    }
}

/**
 * Set the value of numerical scale (with label, spaces...)
 */
function setNumericalScaleValue(scale) {
    var scaleLOV = dijit.byId("scalebarLOV").getChildren();
    var selectedIndex = 0;
    for (var i=0; i<scaleLOV.length; i++) {
    	var currentNodeVal = parseFloat(scaleLOV[i].containerNode.firstChild.nodeValue.replace(/ /g,""));
    	var selectedNodeVal = parseFloat(scaleLOV[selectedIndex].containerNode.firstChild.nodeValue.replace(/ /g,""));
    	if (Math.abs(currentNodeVal - scale) < Math.abs(selectedNodeVal - scale)) {
	    	selectedIndex = i;
    	}
    }
    
    var goodScale = scaleLOV[selectedIndex].containerNode.firstChild.nodeValue;
    
    var newLabel = gMessages["js.message.scalebar.numericalScale.label"] + " &asymp; 1 / " + goodScale;
    var scaleDijit = dijit.byId("scalebarValue");
	scaleDijit.setLabel(newLabel);
}

/**
 * Function called on the bbox event to update the screen.
 */
function updateDisplay(objRef, bbox) {
	// Update the scale combo box
	var currentScale = Math.round(Math.round(objRef.map.getScale()));
	setNumericalScaleValue(currentScale);
}

/**
 * Function called on the srs event to update the screen.
 */
function updateSRSDisplay(objRef) {
	if (objRef) {
		// Update the SRS lov
		var currentSRS = config.objects.mainMap.getSRS();
		var currentContext = getCurrentContext();
		
		if (currentSRS && currentContext) {
			var lovContextObj = dijit.byId("srsLOV");
			
			if (lovContextObj) {
				lovContextObj._hideResultList();
				
				//remove all options
				for (var i=0;i<lovContextObj.store._arrayOfAllItems.length;i++) {
					var current = lovContextObj.store._arrayOfAllItems[i];
					lovContextObj.removeItem(current);
				}
			
				//add the wgs84 option
				lovContextObj.addItem({name:"Longitude/Latitude", value:"EPSG:4326"});
				
				//add the context Options (if not wgs84)
				for (var i=0; i<currentContext.allow_proj_list.length; i++) {
					var code = currentContext.allow_proj_list[i][0];
					var label = currentContext.allow_proj_list[i][1];
					if (code != "EPSG:4326") {
						lovContextObj.addItem({name:label, value:code});
					}
				}
			}
			
			//define the value to display
			for (var i=0;i<lovContextObj.store._arrayOfAllItems.length;i++) {
				var current = lovContextObj.store._arrayOfAllItems[i];
				if (current.value == currentSRS) {
					lovContextObj.setValue(current.name);
				}
			}
			
		}
	}
}

function switchTrackSRS() {
	var selectObj = dijit.byId("srsLOV");
    if (selectObj) {
    	var projName = selectObj.geCurrentItem().value;

    	var trackObj = config.objects.cursorTrack;
    	if (trackObj) {
    		trackObj.setProjectionName(projName[0]);
    	}
    }
}

/**
 * Switch the catalog to display with respect to the selected nomenclature
 */
function switchCategorisedCatalog(nomenclature,label) {
	switch(nomenclature)
	{
	    case INFOTERRE_CATALOG_VIEW :
	    {
			dijit.byId('catalogSwitcher').setLabel(label);
	    	document.getElementById("infoterreCatalogLegend").style.display = '';
	    	document.getElementById("inspireCatalogLegend").style.display = 'none';
	    	document.getElementById("producerCatalogLegend").style.display = 'none';
	    	if (! dijit.byId("infoterreCatalogLegend").domNode.innerHTML) {
	    		dijit.byId("infoterreCatalogLegend").refresh();
	    	}
	        break;
	    }
	    case INSPIRE_CATALOG_VIEW :
	    {
			dijit.byId('catalogSwitcher').setLabel(label);
	    	document.getElementById("infoterreCatalogLegend").style.display = 'none';
	    	document.getElementById("inspireCatalogLegend").style.display = '';
	    	document.getElementById("producerCatalogLegend").style.display = 'none';
	    	if (! dijit.byId("inspireCatalogLegend").domNode.innerHTML) {
	    		dijit.byId("inspireCatalogLegend").refresh();
	    	}
	        break;
	    }
	    case PRODUCER_CATALOG_VIEW :
	    {
			dijit.byId('catalogSwitcher').setLabel(label);
	    	document.getElementById("infoterreCatalogLegend").style.display = 'none';
	    	document.getElementById("inspireCatalogLegend").style.display = 'none';
	    	document.getElementById("producerCatalogLegend").style.display = '';
	    	if (! dijit.byId("producerCatalogLegend").domNode.innerHTML) {
	    		dijit.byId("producerCatalogLegend").refresh();
	    	}
	        break;
	    }
	    default :
	    {
	        // Unknown view
	    }
	}
}

/**
 * Affiche un div bloquant les listeners de mainMapPane, permet de faire glisser le splitter au dessus du div mainMapPane en changeant le z-ibdex du div "divonmap".
 */
function createDivOnMap(){
	var carte=document.getElementById("mainMapPane");
	var newdiv=document.createElement("div");
	newdiv.id="divonmap";
	newdiv.innerHTML="&nbsp;";
	carte.appendChild(newdiv);
}


function changeIndexDivOnMap(indice){
	var divonmap=document.getElementById("divonmap");
	if(indice=="1"){
		divonmap.style.zIndex="2000";
	}
	else {
		divonmap.style.zIndex="0";
		//rafraichit les listes de couches affich?es apr?s d?placement du splitter.
		config.objects.legendTab1.refresh(config.objects.legendTab1);
		config.objects.legendTab2.refresh(config.objects.legendTab2);
	}
}

/**
 * display the subblock to option of the displayed Layers.
 */
function showSubRowLayer(imageId, blockId, imageNameDivOpen, imageNameDivClose, borderId){
	var subRow=document.getElementById(blockId);
	var image=document.getElementById(imageId);
	var border=document.getElementById(borderId);
	var path="style/default/images/";
	if (subRow.style.display=="none"){
		document.getElementById(blockId).style.display = "";
		document.getElementById(imageId).src = path+imageNameDivOpen;//"style/default/images/flech_noir_bas.gif";
		if(border!=null){
			for(var i=0; i<border.childNodes.length;i++){
			document.getElementById(borderId).childNodes[i].style.borderBottom = "1px solid #A19A95";
			}
		}
	}
	else{
		document.getElementById(blockId).style.display = "none";
		document.getElementById(imageId).src = path+imageNameDivClose;// "style/default/images/flech_noir_dte.gif";
		if(border!=null){
			for(var i=0; i<border.childNodes.length;i++){
			document.getElementById(borderId).childNodes[i].style.borderBottom = "";
			}
		}
	}
}

/**
 * Set the scale displayed in the scale combo box if valid.
 */
function setScaleFromCombo(newScale) {
    if(newScale) {
        // Control the input value
        if(config.objects.mainMap) {
            itZoomToScale(config.objects.mainMap.map.getCenter(), newScale);
        }
    }
}

/**
 * Create an opacityBar to each layer and allow to manage in opacity
 */
function buildOpacityBar(contextString, context, uuid, layerId, opacityLabel){
	var divOpacity = document.getElementById("divOpacity_" + layerId);
	var divOpacityText = document.getElementById("opacityText_" + layerId);
	var opacityValue = context.getOpacity(layerId);
	
	if(!opacityValue)
		opacityValue = 1;

	if(divOpacity.innerHTML.indexOf('nbsp') > -1){
		var inner = "<div id=\"opacityText_" + layerId + "\" class=\"opacityText\">" + opacityLabel + "</div>";
		inner += "<div id=\"opacityTracker_" + layerId + "\" class=\"opacityValue\">" + (opacityValue * 100).toString().substring(0,3) + "%</div>";
		inner += "<div id=\"opacitySlider_" + layerId + "\" dojoType='infoterre.widget.HorizontalSliderMove' class='opacitySlider' minimum='0.0' maximum='1.0' value='1.0' discreteValues='11' intermediateChanges='false' showButtons='false' onSliderMove=\"" + contextString + ".setOpacity('" + layerId + "',this.getValue());document.getElementById('opacityTracker_" + layerId + "').innerHTML = (this.getValue() * 100).toString().substring(0,3) + '%';\" onSliderReleased=\"notifyOpacityModification('" + uuid + "', this.getValue().toString().substring(0,3));\" ></div>";			
		divOpacity.innerHTML = inner;
		var lov = ["opacityText_" + layerId,
			"opacityTracker_" + layerId,
			"opacitySlider_" + layerId];
		destroyDijits(lov);
		dojo.parser.parse(divOpacity);
		dijit.byId("opacitySlider_" + layerId).setValue(opacityValue);
	}
}

/**
 * Create the Variation Bar to each layer
 */
function buildSLDBar(layerId, variationLabel) {
	var divVariation = document.getElementById("divVariation_" + layerId);
	if (divVariation && (divVariation.innerHTML.indexOf('nbsp') > -1)) {
		var removeDiv = true;
		//test si le div n'est pas deja rempli
		var divAdd = document.getElementById("SLDAddDiv_" + layerId);
		var layerObj = config.objects.mainMap.getLayer(layerId);
		
		if (!divAdd && layerObj) {
			
			//regarde si il y a plusieurs styles associés au layer
			var listOfStyle = layerObj.selectNodes("wmc:StyleList/wmc:Style");
			
			var innerSelect = "";
			
			if (listOfStyle.length > 1) {
				removeDiv = false;
				innerSelect += "<select dojoType=\"dijit.form.FilteringSelect\" id=\"SLDStyleSelect_" + layerId + "\" class=\"SLDStyleSelect\" autocomplete=\"false\" onChange=\"manageSLDButton('" + layerId + "');setStyle('" + layerId + "');\">";
				
				var listOfStyle = layerObj.selectNodes("wmc:StyleList/wmc:Style");
				for (var i=0; i<listOfStyle.length; i++) {
					var style = listOfStyle[i];
					var styleName = "";
					var styleValue = "";
					var editable = false;
					
					var current = style.getAttribute("current");
					var selected = (current == "1") ? "selected=\"selected\" " : "";
	
					var sldNode = style.selectSingleNode("wmc:SLD");
					if (!sldNode) {
						styleName = style.selectSingleNode("wmc:Name").firstChild.nodeValue;
						styleValue = styleName;
					} else {
						styleName = sldNode.selectSingleNode("wmc:Name").firstChild.nodeValue;
						var sldUrl = sldNode.selectSingleNode("wmc:OnlineResource").getAttribute("xlink:href");
						editable = (sldUrl && sldUrl.indexOf('ref') == -1);
						styleValue = sldUrl;
					}
					innerSelect += "<option value=\"" + styleValue + "|" + editable + "\"" + selected + ">" + styleName + "</option>";
					
				}
				innerSelect += "</select>";
			}
			
			//regarde si il y a une collection de champ associé au layer
			var hasFeature = false;
			var catalogLayerId = layerObj.selectSingleNode("wmc:Extension/wmc:Infoterre/wmc:UnderlyingUUID").firstChild.nodeValue;
			var geomType = "";
			dojo.xhrGet({
				url : "./feature?method=hasFeature&layerId=" + escape(catalogLayerId),
				handleAs: "json",
				sync: true,
				load: function(responseObject, ioArgs) {
					hasFeature = responseObject.hasFeature;
					if (hasFeature) {
						geomType = responseObject.geomType;
					}
					return responseObject;
				},
				error: function(response, ioArgs) {
					console.error("HTTP status code: ", ioArgs.xhr.status);
				}
			});
	
			if (hasFeature) {
				removeDiv = false;
				var inner = "<div class=\"variationText\">" + variationLabel + "&nbsp;:</div>";
				
				inner += "<div id=\"SLDAddDiv_" + layerId + "\" class=\"SLDADDDiv\"><input type=\"hidden\" id=\"SLDGeomType_" + layerId + "\" value=\"" + geomType + "\"><button id=\"SLDAddButton_" + layerId + "\" dojoType=\"dijit.form.Button\" onClick=\"addSLD('" + layerId + "')\" iconClass=\"SLDAddIcon\" showLabel=\"false\" class=\"SLDAddRuleButton\">Add</button></div>";
				inner += "<div id=\"SLDRuleDiv_" + layerId + "\" class=\"SLDRuleDiv\">";
				inner += "<button id=\"SLDDelRuleButton_" + layerId + "\" class=\"SLDDelRuleButton\" dojoType=\"dijit.form.Button\" onClick=\"delSLDButton('" + layerId + "')\" iconClass=\"SLDDelIcon\" showLabel=\"false\">Del</button>";
				inner += "<button id=\"SLDEditRuleButton_" + layerId + "\" class=\"SLDEditRuleButton\" dojoType=\"dijit.form.Button\" onClick=\"editSLD('" + layerId + "')\" iconClass=\"SLDEditIcon\" showLabel=\"false\">Edit</button>";
		
				inner += innerSelect;

				inner += "</div>"
				
				divVariation.innerHTML = inner;
			}

			//supprime le div si il n'y a pas d'information � afficher
			if (removeDiv) {
				divVariation.parentNode.removeChild(divVariation);
			} else {
				//detruit les dijits au cas o� ils existeraient. Cela arrive sur un resize du menu de droite
				var lov = ["SLDAddButton_" + layerId,
					"SLDStyleSelect_" + layerId,
					"SLDEditRuleButton_" + layerId,
					"SLDDelRuleButton_" + layerId];
				destroyDijits(lov);

				dojo.parser.parse(divVariation);
				manageSLDButton(layerId);
			}
		}
	}
}

function setStyle(layerId) {
	var SLDselect = dijit.byId("SLDStyleSelect_" + layerId);
    var selectedIndex = SLDselect.item._0;
    var mbContext = config.objects.mainMap;
	mbContext.setCurrentStyle(mbContext,layerId,selectedIndex);
}

/**
 * Manage the SLD buttons (Edit and Del)
 */
function manageSLDButton(layerId) {
	var SLDselect = dijit.byId("SLDStyleSelect_" + layerId);
	
	var disable = true;
	
	if (SLDselect) {
		var selectedValue = SLDselect.getValue();
		if (selectedValue.indexOf('|') > -1) {
			var values = selectedValue.split('|');
			disable = (values[1] == "false");
		}
	}
	
	dijit.byId("SLDDelRuleButton_" + layerId).setDisabled(disable);
	dijit.byId("SLDEditRuleButton_" + layerId).setDisabled(disable);
}

/**
 * Update the SLDBar
 */
function updateSLDBar(layerId) {	
	var variationLabel = document.getElementById("divVariation_" + layerId).firstChild.innerHTML;
	variationLabel = variationLabel.replace(/&nbsp;:/,"");
	var divVariation = document.getElementById("divVariation_" + layerId);
	divVariation.innerHTML = 'nbsp';
	buildSLDBar(layerId, variationLabel);
}

function resizeTabContainer(){
	var tabsContent = document.getElementsByTagName('div');
	for(i=0;i<tabsContent.length;i++){
		if(tabsContent[i].className == "dijitTabPaneWrapper dijitAlignClient"){
			tabsContent[i].style.width = "100%";
		}
	}
}

/**
 * Display the mainPage (hide splashscreen if any, loading screen if any...)
 */
function showMainPage() {
    document.getElementById("mainScreen").style.visibility = "visible";
	hideLoadingScreen();
	// If the source is "Geocatalogue"
	if (source == "Geocatalogue") {
		dijit.byId("GeocatalogueDialogBox").show();
	}
}

/**
 * Hide the Loading screen (if any)
 */
function hideLoadingScreen() {
	var screen = document.getElementById("loadingScreen");
	if (screen) {
		screen.style.display = "none";
	}
}

/**
 * Met a jour le locator
 */
function updateLocator() {
	var currentLocatorURL = config.objects.locator.url;
	var currentContextLocatorURL = getCurrentContext().locator_url;
	if (currentLocatorURL != currentContextLocatorURL) {
		config.loadModel('locator', currentContextLocatorURL);
	}
	var bbox = config.objects.mainMap.map.getExtent().toBBOX().split(',');
	var ul = new Array(bbox[0],bbox[3]);
	var lr = new Array(bbox[2],bbox[1]);
	var newAoi = new Array(ul, lr);
	config.objects.locator.setParam("aoi", newAoi);
}

/**
 * Detruit une liste d'objet
 */
function destroyDijits(lov) {
	for (var i=0;i<lov.length;i++) {
		if (dijit.byId(lov[i]))
			dijit.byId(lov[i]).destroy();
	}
}

/**
 * Enleve les fils d'une liste d'objet
 */
function removeChildrenDijits(father, lov) {
	for (var i=0;i<lov.length;i++) {
		if (dijit.byId(father))
			dijit.byId(father).removeChild(lov[i]);
	}
}

/**
 * Centre un dijit sur l'ecran
 */
function centerDijit(dijitObj) {
	centerDiv(dijitObj.domNode);
}

/**
 * Centre un DIV sur l'ecran
 */
function centerDiv(divObj) {
	var viewport = dijit.getViewport();
	var mb = dojo.marginBox(divObj);

	var style = divObj.style;
	var newLeft = Math.floor((viewport.l + (viewport.w - mb.w)/2));
	if (newLeft < 0) newLeft = 0;
	var newTop = Math.floor((viewport.t + (viewport.h - mb.h)/2));
	if (newTop < 0) newTop = 0;
	style.left = newLeft + "px";
	style.top = newTop + "px";
}