// $Id: section.js,v 1.9 2010/02/08 10:29:16 mauclerc Exp $

var gInfoterreSections = new InfoterreSections();

/**
 * Object that represents a list of sections
 */
function InfoterreSections() {

    // Properties
    this.sections = new Array();

    // Methods
    this.getSection=function(id){
		for (var i=0; i<this.sections.length; i++) {
			var section = this.sections[i];
			if (section.id == id) {
				return section;
			}
		}
        return null;
    }

    this.addSection=function(section){
    	this.sections.push(section);
    	refreshSectionList();
    	section.makeBuffer();
    }

    this.removeSection=function(id){
    	for(var i = this.sections.length - 1; i >= 0; i--) {
        	if(this.sections[i].id == id) {
        		this.sections[i].getFeature().destroy();
            	this.sections.splice(i,1);
            	//break;more than once??
        	}
    	}
    	refreshSectionList();
    }
    
    this.getLayer=function(targetLayerName) {
    	var coupeLayer;
		var layerList = config.objects.mainMap.map.getLayersByName(targetLayerName);
		if (layerList.length > 0)
        	coupeLayer = layerList[0];
        if (!coupeLayer){
            coupeLayer = new OpenLayers.Layer.Vector(targetLayerName, {style: this.defaultStyle});
            config.objects.mainMap.map.addLayer(coupeLayer);
        }
        return coupeLayer;
    }
    
    this.restoreSections=function() {
    	if (config && config.objects && config.objects.editSection && config.objects.editSection.targetLayer)
    	var targetLayerName = (config.objects.editSection.targetLayer.text) ? config.objects.editSection.targetLayer.text : config.objects.editSection.targetLayer.textContent;
		if (targetLayerName) {
	    	var sectionLayer = this.getLayer(targetLayerName);
	    	if (sectionLayer) {
		       	for (var i=0;i<this.sections.length; i++) {
		       		var section = this.sections[i]
		       		if (section.savedFeature) {
						var clonedFeature = cloneSectionFeature(section.savedFeature);
						if (section.EPSG != getCurrentContext().projection) {
							var projSource = new OpenLayers.Projection(section.EPSG);
							var projDest = new OpenLayers.Projection(getCurrentContext().projection);
						
							clonedFeature.geometry.transform(projSource, projDest);
						}
		       			sectionLayer.addFeatures(clonedFeature);
		       		}
		       	}
	    	}
		}
    }
}

/**
 * Object that represents a section
 */
function InfoterreSection(sectionObj, iName) {
	//bufferService Url
	this.bufferService = "./buffer";

	//service GDM
	this.serviceUrl = "http://infoterre.brgm.fr/coupe/service/coupeProfilService?";

    // Properties
    this.id = sectionObj.id; // Id of the feature
    this.name = iName;
    this.points = new Array();
    this.extensionLeft = 50;
    this.extensionRight = 50;
    this.scaleX = null;
    this.scaleY = null;
    this.width = 500;
    this.lastResult = null;
    this.wktParser = new OpenLayers.Format.WKT();
    this.buffer = null;
    this.savedFeature = cloneSectionFeature(sectionObj);
	this.EPSG = getCurrentContext().projection;

    // Methods
    this.getFeature = function() {
    	// Get the layer and the geometry
    	var targetLayerName = (config.objects.editSection.targetLayer.text) ? config.objects.editSection.targetLayer.text : config.objects.editSection.targetLayer.textContent;
    	
    	var layer = config.objects.mainMap.map.getLayersByName(targetLayerName)[0];
    	if (layer)
    		return layer.getFeatureById(this.id);
    	return null;
    }

    this.getUrl = function() {
    	// Get the feature
    	var feature = this.getFeature();
    	// Build the URL 
    	var url = this.serviceUrl;
		// Coordinates
		var xPoints = "";
		var yPoints = "";
    	for(var i = 0; i < feature.geometry.components.length; i++) {
    		xPoints += feature.geometry.components[i].x;
    		yPoints += feature.geometry.components[i].y;
    		if (i != (feature.geometry.components.length - 1)) {
	    		xPoints += ";";
	    		yPoints += ";";
    		}
    	}
    	url += "XPoints=" + xPoints + "&";
    	url += "YPoints=" + yPoints + "&";
    	// Width
    	if (this.width) {
	    	url += "Width=" + this.width + "&";
	    }
    	// Extensions
    	if (this.extensionLeft) {
	    	url += "LeftExtension=" + this.extensionLeft + "&";
    	}
    	if (this.extensionRight) {
	    	url += "RightExtension=" + this.extensionRight + "&";
    	}
    	// Extensions
    	if (this.scaleX) {
	    	url += "ScaleX=" + this.scaleX + "&";
    	}
    	if (this.scaleY) {
	    	url += "ScaleY=" + this.scaleY + "&";
    	}
        
        return url;
    }

    this.request = function() {
    	enableSectionImage();
	    document.getElementById("sectionResult").innerHTML = "<img src=\"./customapbuilder/skin/infoterre/images/Loading.gif\"/>";
    
		dojo.xhrGet({
			url: this.getUrl(),
			handleAs: "json",
            section: this,
			load: this.handleResponse
		});
    }

    this.edit = function() {
    	// Copy every values
    	document.getElementById("sectionId").value = this.id;
    	document.getElementById("sectionName").value = this.name;
    	document.getElementById("sectionWidth").value = this.width;
    	document.getElementById("sectionExtensionLeft").value = this.extensionLeft;
    	document.getElementById("sectionExtensionRight").value = this.extensionRight;
    	
    	dijit.byId('sectionScaleX').labelAttr = "label";
    	dijit.byId('sectionScaleY').labelAttr = "label";
    	
    	dijit.byId('sectionScaleX').setValue(this.scaleX);
    	dijit.byId('sectionScaleY').setValue(this.scaleY);
    	if (this.lastResult) {
			if (this.lastResult.error != " ") {
				document.getElementById("sectionResult").innerHTML = this.lastResult.error;
			} else {
		    	document.getElementById("sectionResult").innerHTML = "<img id=\"sectionResultImage\" style=\"border:0;\" src=\"" + this.lastResult.url + "\" usemap=\"#lithologyMap\" onLoad=\"refreshSectionBlock()\">";
                var mapString = "<map name=\"lithologyMap\">";
                for(var i in this.lastResult.components) {
                    var component = this.lastResult.components[i];
                    mapString += "<area style=\"border: 1px solid black;\" shape=\"rect\" coords=\"" + component.position.x_min + "," + component.position.y_max + "," + component.position.x_max + "," + component.position.y_min + "\" href=\"http://ficheinfoterre.brgm.fr/InfoterreFiche/ficheBss.action?id=" + component.reference + "\" alt=\"" + component.lithologie + "\" title=\"" + component.lithologie + "\" target=\_blank\" />";
                }
                mapString += "</map>";
                document.getElementById("sectionResult").innerHTML += mapString;
			}
    	} else {
	    	document.getElementById("sectionResult").innerHTML = "";
    	}
    	refreshSectionBlock();
    }
    
    this.highlight = function() {
    	if (this.savedGeom != null) {
    		gInfoterreSections.restoreSections();
    	}
    
        var sectionHighlightStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
        sectionHighlightStyle.strokeColor = "red";
        sectionHighlightStyle.strokeWidth = 5;
        sectionHighlightStyle.graphicOpacity = 1;
        sectionHighlightStyle.fillColor = "red";
        sectionHighlightStyle.fillOpacity = 0.3;
    	var feature = this.getFeature()
    	feature.style = sectionHighlightStyle;
        var targetLayer = feature.layer;
        sectionHighlightStyle.strokeWidth = 2;
        this.buffer.style = sectionHighlightStyle;
        targetLayer.addFeatures(this.buffer);
        targetLayer.redraw();
    }

    this.unhighlight = function() {
    	var feature = this.getFeature();
    	feature.style = null;
    	var targetLayer = feature.layer;
        this.buffer.style = null;
    	targetLayer.removeFeatures(this.buffer);
        targetLayer.redraw();
    }
    
    // Warning : "this" is not the section but the request of XHR method
    this.handleResponse = function(responseObject) {
        // Store the result
        this.section.lastResult = responseObject;
        // Copy parameters back
        if (this.section.lastResult.error == " ") {
	        this.section.extensionLeft = this.section.lastResult.parameters.extensions[0];
	        this.section.extensionRight = this.section.lastResult.parameters.extensions[1];
	        this.section.scaleX = this.section.lastResult.parameters.scaleX;
	        this.section.scaleY = this.section.lastResult.parameters.scaleY;
	        this.section.width = this.section.lastResult.parameters.width;
	    }
        // Re-edit
        this.section.edit();
    }
    
    this.setProperty = function(property, value) {
		// Set the property
		switch(property) {
   			case "name":
   				this.name = value;
   				refreshSectionList();
				break;
   			case "extensionLeft":
   				this.extensionLeft = value;
				//refresh the buffer
				this.makeBuffer();
				break;
   			case "extensionRight":
   				this.extensionRight = value;
				//refresh the buffer
				this.makeBuffer();
				break;
   			case "scaleX":
   				this.scaleX = value;
				break;
   			case "scaleY":
   				this.scaleY = value;
				break;
   			case "width":
   				this.width = value;
				//refresh the buffer
				this.makeBuffer();
				break;
		}
		disableSectionImage();
    }
    
    this.makeBuffer = function() {
    	var feature = cloneSectionFeature(this.savedFeature);
       	//convert in 27582 If necessary
       	if (this.EPSG != "EPSG:27582") {
			var projSource = new OpenLayers.Projection(this.EPSG);
			var projDest = new OpenLayers.Projection("EPSG:27582");
			feature.geometry.transform(projSource, projDest);
		}
       	var wktFeature = this.wktParser.write(feature);
       	
       	//make the params
       	var params = {
       		geometry : wktFeature,
       		distance : this.width,
       		ext_start : this.extensionLeft,
       		ext_end : this.extensionRight
       	};
       	
		dojo.xhrPost({
			url: this.bufferService,
			handleAs: "text",
			content: params,
            section: this,
			load: this.handleBufferResponse
		});
    }
       	
    this.handleBufferResponse = function(responseObject) {
    	//this is the request of XHR method
    	var bufferWKT = responseObject;
    	this.section.buffer = this.section.wktParser.read(bufferWKT);
    }
    
}

function cloneSectionFeature(feature) {
	var forcedId = feature.id;
	var clone = feature.clone();
	clone.id = forcedId;
	return clone;
}

function refreshSectionList() {
   	var sectionHTML = "";
   	for(var i=0;i<gInfoterreSections.sections.length;i++) {
		var section = gInfoterreSections.sections[i];
		
		sectionHTML += "<div class=\"layerUnitPane\"><table cellspacing=\"0\" cellpadding=\"5\" border=\"0\" width=\"100%\"><tbody><tr>";
		sectionHTML += "<td class=\"layerFirstRowCell\"><a class=\"mbButton\" href=\"javascript: gInfoterreSections.removeSection('" + section.id + "');\"><img border=\"0\" src=\"./customapbuilder/skin/infoterre/images/default/layer_butt_remove.gif\" title=\"Supprimer cette section\"/></a></td>";
		sectionHTML += "<td class=\"titleCell_true layerFirstRowCell\" style=\"cursor:pointer;\" width=\"100%\" onmouseover=\"javascript: gInfoterreSections.getSection('" + section.id + "').highlight();\" onmouseout=\"javascript: gInfoterreSections.getSection('" + section.id + "').unhighlight();\" onclick=\"javascript: gInfoterreSections.getSection('" + section.id + "').edit();\">" + section.name + "</td>";
		sectionHTML += "</tr></tbody></table></div>";
	}
    document.getElementById("sectionList").innerHTML = sectionHTML;
}

function refreshSectionBlock() {
	enableSectionImage();
	var sectionDialog = dijit.byId('SectionDialogBox');
	
	if (sectionDialog) {
		if (document.getElementById("sectionResultImage") && document.getElementById("sectionResultImage").offsetWidth > 0) {
			var newSize = document.getElementById("sectionResultImage").offsetWidth + 20;
			if (newSize < 500) newSize = 500;
			sectionDialog.domNode.style.width = newSize + "px";
		}
		sectionDialog.show();
		centerDijit(sectionDialog);
	}
}

function disableSectionImage() {
	var sectionImage = document.getElementById("sectionResultImage");
	if (sectionImage) {
		var masque = document.getElementById("sectionMasque");
		if (masque) {
			masque.style.height = sectionImage.offsetHeight;
			masque.style.width = sectionImage.offsetWidth;
			masque.style.top = sectionImage.offsetTop;
			masque.style.left = sectionImage.offsetLeft;
			masque.style.visibility = 'visible';
			masque.style.display = 'block';
		}
	}
}

function enableSectionImage() {
	var masque = document.getElementById("sectionMasque");
	if (masque) {
		masque.style.visibility = 'hidden';
		masque.style.display = 'none';
	}	
}

function scaleSectionLabelUpdate(item, store) {
	var label = store.getValue(item, 'label');
	label = label.replace("&asymp;","≈");
	return label;
}

function moveToTopSectionLayer() {
   	var targetLayerName = (config.objects.editSection.targetLayer.text) ? config.objects.editSection.targetLayer.text : config.objects.editSection.targetLayer.textContent;
	if (targetLayerName) {
    	var sectionLayer = config.objects.mainMap.map.getLayersByName(targetLayerName)[0];

    	if (sectionLayer) {
    		var nbLayer = config.objects.mainMap.map.getNumLayers();
    		config.objects.mainMap.map.setLayerIndex(sectionLayer,nbLayer-1);
    	}
    }
}