

/**
 * @requires core/Control.js
 */

/**
 * Class: OpenLayers.Control.Info
 *
 * Inherits from:
 *  - <OpenLayers.Control>
 */
eGV.Control.InfoCustom = OpenLayers.Class(eGV.Control.Info, {

    /**
     * Property: type
     * {String} The type of <OpenLayers.Control> -- When added to a 
     *     <Control.Panel>, 'type' is used by the panel to determine how to 
     *     handle our events.
     */
    type: OpenLayers.Control.TYPE_TOOL,
	
    /**
     * APIProperty: Map object
     * {<OpenLayers.Map>} 
     */	
    map: null,

    /**
     * Property: div
     * (div Object)
     */		
    div: null,
		
    /**
     * Property: pinURL
     * (String)
     */
    pinURL: eGV.scriptRoot +"../client/egv/theme/default/img/pingreen.gif",

    /**
     * Property: pinSize
     * (<OpenLayers.Size>)
     */
    pinSize: new OpenLayers.Size(30, 30),
    /**
     * Property: pinSize
     * (<OpenLayers.Size>)
     */
    pinOffset: new OpenLayers.Pixel(0,-30),
						
    /**
     * Property: infoURL
     * (String)
     */
    infoURL: null,
		
    /**
     * Property: loadingMessage
     * (String)
     */
    loadingMessage: "Carregant informació",
		
    /**
     * Property: nothingFoundMessage
     * (String)
     */
    nothingFoundMessage: "No s'ha trobat informació",
		
  
    /**
     * Property: currentConnection
     * (eGV.connection)
     */
    currentConnection : false,
    /** 
     * Property: viewall
     * (eGV.connection)
     */
    viewall : true,
	  
    /** 
     * Property: nothingFound
     * (array)
     */
    nothingFound : null,

    /**
     * Property: markers
     * {OpenLayers.Layer.Markers} the layer on which the pin marker(s)
     * is drawn
     */
    markers: null,
    
    /**
     * Method: initialize
     */    
     
    initialize: function(div, options){
        options = options || [];
        eGV.Control.prototype.initialize.apply(this, [options]);
        if (!options.displayClass)
            this.displayClass =
            this.CLASS_NAME.replace("eGV.", "egv").replace(/\./g, "");

        //Set div
        this.div = document.getElementById(div);

        //Set map
        this.setMap();

        this.handler = new OpenLayers.Handler.Click( this,
        {
            click: this.handleClick
            });
        this.nothingFound = new Array();
    },


    /**
     * Method: setMap
     */	
    setMap: function() {
        eGV.Control.prototype.setMap.apply(this);
        return this.map;
    },	
    
    /**
     * Method: handleClick
     */
    handleClick: function(evt){
        this.getInfo(evt.xy.x,evt.xy.y);
    },

    getInfoFromCoordinates: function(x,y){
        var pixel = this.map.getPixelFromLonLat(new OpenLayers.LonLat(x,y));
        this.getInfo(pixel.x,pixel.y);
    },

    /**
     * Method: getInfo
     */
    getInfo: function(x,y){
        this.events.triggerEvent("actionstart");
        this.nothingFound.splice(0, this.nothingFound.length);
        this.drawPin(x,y, this.pinURL);
        this.drawStructure();
        var index = 0;
        this.drawWaiting();

        for (var i = 0; i < this.map.connections.length; i++) {
            if (this.isConnectionQueryable(this.map.connections[i])) {
                this.infoURL = this.map.connections[i].getFeatureInfoUrl(x, y);
                this.doRequest(this.infoURL, index, i);
                index++;
            }
        }
        this.checkNothingFound();
        this.events.triggerEvent("actionend");
    },


    drawPin: function(x,y,url){
        if (this.markers != null) {
            this.map.removeLayer(this.markers);
            this.markers = null;
        }
        this.markers = new OpenLayers.Layer.Markers("Markers");
        this.map.addLayer(this.markers);
        var offset = this.pinOffset;
        var size = this.pinSize;
        var icon = new OpenLayers.Icon(url, size, offset);
        var pixel = new OpenLayers.Pixel(x, y);
        var lonlat = this.map.getLonLatFromPixel(pixel);
        this.markers.addMarker(new OpenLayers.Marker(lonlat, icon));
        this.markers.addMarker(new OpenLayers.Marker(lonlat, icon.clone()));
    },

    removePin: function(){
        if (this.markers != null) {
            this.map.removeLayer(this.markers);
            this.markers = null;
        }
    },
		
    getNumQueryableConnections:function(){
        var response = 0;
        for (var i=0, len=this.map.connections.length ;i < len; i++){
            if (this.isConnectionQueryable(this.map.connections[i]) == true) {
                response++;
            }
        }
        return response;
    },
		
    drawStructure: function(){
			
        //Main div
        var divMain = document.createElement("div");
        divMain.className = "egvControlInfoDiv";
            

        var divIntro = document.createElement("div");
        divIntro.setAttribute("class","divIntroLayersManager");
        divIntro.setAttribute("className","divIntroLayersManager"); // IE made do this!
				
        var txtNode = document.createTextNode("Feu servir els botons de gestor de capes  ");
        divIntro.appendChild(txtNode);
        var img = document.createElement("img");
        img.setAttribute("src","img/viewer/layers_petit.png");
        img.setAttribute("class","imgIntroLayersManager");
        img.setAttribute("className","imgIntroLayersManager");
        img.setAttribute("align","absmiddle");
				
        // works fine with ff but not in IE
        //img.setAttribute("click","layerManagerFuncion();");
			  
        // so we have to do it like this.
        if (document.addEventListener)
        { // All browsers except IE use these assignments
            img.addEventListener("click",layerManagerFuncion,false);
        }
        else
        { // this part is needed for IE only
            img.attachEvent("onclick",layerManagerFuncion);
        }
			  
			  
					



        divIntro.appendChild(img);
				
        var txtNode = document.createTextNode("  i el gestor per afegir serveis WMS  ");
        divIntro.appendChild(txtNode);
        var img2 = document.createElement("img");
        img2.setAttribute("src","img/viewer/w_petit.png");
        img2.setAttribute("class","imgIntroLayersManager");
        img.setAttribute("className","imgIntroLayersManager");
        img2.setAttribute("align","absmiddle");

        // works fine with ff but not in IE
        //img.setAttribute("click","wmsControlCall();");
			  
        // so we have to do it like this.
        if (document.addEventListener)
        { // All browsers except IE use these assignments
            img2.addEventListener("click",wmsControlCall,false);
        }
        else
        { // this part is needed for IE only
            img2.attachEvent("onclick",wmsControlCall);
        }



        divIntro.appendChild(img2);
				
        var txtNode = document.createTextNode("  per tornar a carregar-los en pantalla");
        divIntro.appendChild(txtNode);
				
        divMain.appendChild(divIntro);
            
            

        // ul containing elements for different connections
        var ulInfoStructure = document.createElement("ul");
        ulInfoStructure.id = "ulInfoStructure";
        ulInfoStructure.className = "egvControlInfoStructureUl";
				
        for(var i = 0, len = this.getNumQueryableConnections(); i < len ;i++){
            var liInfoStructure = document.createElement("li");
            liInfoStructure.id = "liInfoStructure_"+i.toString();
            txtInfoStructure = document.createTextNode("");
            liInfoStructure.appendChild(txtInfoStructure);
            ulInfoStructure.appendChild(liInfoStructure);
            this.nothingFound.push(1);
        }
        divMain.appendChild(ulInfoStructure);
        //clears divInfo
        this.clearInnerHTML(this.div);
        //sets news values
        this.div.appendChild(divMain);
			
    },
		
    drawWaiting:function(){
        for(var index = 0, len = this.getNumQueryableConnections(); index < len ;index++){
            var liString = "liInfoStructure_"+index.toString();
            var liWaiting = document.getElementById(liString);
            this.clearInnerHTML(liWaiting);
            liWaiting.appendChild(document.createTextNode(this.loadingMessage));
            liWaiting.className = "egvControlInfoWaitingLi";
        }
    },
				
    isConnectionQueryable: function(conn){
        if (conn.type == "WMS" && conn.queryable == true && conn.visibleLayers.length > 0){
            for (i = 0 ; i< conn.layers.length; i ++){
                if (conn.layers[i].queryable == true){
                    return true;
                }
            }
            return false;
        }else{
            return false;
        }
    },
		
    doRequest: function(url, index, connection){

        var XHR = OpenLayers.Request.POST ({
            //url: eGV._getScriptLocation() +"../../viewer-3.0/server/egv/info.php",
            url: eGV.scriptRoot +"../server/egv/info/info.php",
            data: "AJAX request to get information from clicked layers",
            params: {
                req: this.infoURL
                },
            async : true,
            headers: {
                "Content-Type": "text/plain"
            },
            success: function() {
                this.drawResults(XHR,index, connection)
            },
            failure: function(){
                this.serverFailure(index)
                },
            scope: this
        });
    //alert(url);
    },
    serverFailure: function(index)
    {
        var liString = "liInfoStructure_"+index.toString();
        var liElement = document.getElementById(liString);
        liElement.parentNode.removeChild(liElement);
    },
    drawResults: function(XHR,index, connIndex){
			
        var connection = this.map.connections[connIndex];
        var liString = "liInfoStructure_"+index.toString();
        var liElement = document.getElementById(liString);
			
			
        //var data = eval('(' + XHR.responseText + ')');
        var olJSON = new OpenLayers.Format.JSON();
        response = XHR.responseText.replace(/\\\'/g,"'");
        response = response.replace(new RegExp( "\\n", "g" ), "");
        response = response.replace(new RegExp( "\\r", "g" ), "<br />");
			 
        var data = olJSON.read(response);
        //alert(response);
	    
        if (data==null)
        {
            liElement.parentNode.removeChild(liElement);
            this.nothingFound[index]=0;
        }
        else
        {
            var divMain = document.createElement("div");
            divMain.className = "egvControlInfoDiv";
					
					
            if (data.length == 0){
                liElement.parentNode.removeChild(liElement);
                this.nothingFound[index]=0;
                this.checkNothingFound();
                return 0;
            }else{
                this.nothingFound[index]=1;
            }
					
											
            //Main list
            tableInfo = document.createElement("table");
            tableInfo.width = "100%";
            tableInfo.cellpadding = "0";
            tableInfo.cellspacing = "0";
            tableInfo.className = "egvControlInfoDiv";
		            
            tbodyInfo = document.createElement("tbody");

            var divInfoTitle;

            // iterating thru layers requested
            for (var i = 0, len = data.length; i < len; i++) {
		
                var nameLayer = (data[i].layer!="") ? data[i].layer : connection.layers[0].name;
                var layer = connection.getLayerByName(nameLayer);
                trInfo = document.createElement("tr");
                tdInfoTitle = document.createElement("td");
                tdInfoTitle.colSpan = "2";
                divInfoTitle = document.createElement("div");
                divInfoTitle.className = "egvControlInfoDivLayerTitle";
							
                var txtInfoTitle = data[i].layer;
							
                if(layer!=null)
                {
                    txtInfoTitle=(layer.title!="") ? layer.title : data[i].layer;
                }
                divInfoTitle.appendChild(document.createTextNode(txtInfoTitle));
                tdInfoTitle.appendChild(divInfoTitle);
                trInfo.appendChild(tdInfoTitle);
                tbodyInfo.appendChild(trInfo);

                if (data[i].type == "html") {
                    trInfoHTML = document.createElement("tr");
                    tdInfoHTML = document.createElement("td");
                    tdInfoHTML.colspan = 2;
                    divInfoHTML = document.createElement("div");
                    divInfoHTML.className = "egvControlInfoDivLayerHTML";
                    var htmlText = data[i].fields[0].replace(/<a/g,"<a target=blank");
                    divInfoHTML.innerHTML = htmlText;
                    tdInfoHTML.appendChild(divInfoHTML);
                    trInfoHTML.appendChild(tdInfoHTML);
                    tbodyInfo.appendChild(trInfoHTML);
                }
                else {
                    //info fields
                    var field;
                    var visible;
                    var islink;
							
                    for (var j = 0, dataLen = data[i].fields.length; j < dataLen; j++) {
							
                        field = null;
                        visible = true;
                        islink = false;
								
                        if (layer.fieldList != null) {
                            field = layer.fieldList.getFieldByName(data[i].fields[j].name);
                            if (field != null) {
                                visible = field.visible;
                            }
                        }
                        if (this.viewall == false && field == null)
                            visible = false;
                        if (field != null) {
                            if (data[i].fields[j].value == "" && field.ommitEmpty == true)
                                visible = false;
                        }
                        if (visible == true) {
                            trInfoField = document.createElement("tr");
                            //trInfoField.vAlign = "left";
									
                            tdInfoFieldTitle = document.createElement("td");
                            divInfoFieldTitle = document.createElement("div");
                            divInfoFieldTitle.className = "egvControlInfoDivLayerFieldTitle";
                            txtInfoFieldTitle = (field != null) ? field.alias : data[i].fields[j].name;
                            divInfoFieldTitle.appendChild(document.createTextNode(txtInfoFieldTitle));
                            // quan les layers tinguin fieldlist s'han de canviar aquestes dues lï¿½nies.
									
									
                            tdInfoFieldTitle.appendChild(divInfoFieldTitle);
									
                            tdInfoFieldValue = document.createElement("td");
                            divInfoFieldValue = document.createElement("div");
                            divInfoFieldValue.className = "egvControlInfoDivLayerFieldValue";
									
                            if(((String(data[i].fields[j].value).toLowerCase().indexOf("http://"))==0)||(String(data[i].fields[j].value).toLowerCase().indexOf("www")==0)||(String(data[i].fields[j].value).toLowerCase().indexOf("https://")==0))
                            {
										
                                aInfoFieldLink = document.createElement("a");
                                aInfoFieldLink.className = "egvControlInfoLink";
                                if ((data[i].fields[j].value.toLowerCase().indexOf("www")==0))
                                {
                                    aInfoFieldLink.href = "http://"+data[i].fields[j].value;
				
                                }
                                else
                                {
                                    aInfoFieldLink.href = data[i].fields[j].value;
                                }
                                if(field!=null)
                                {
                                    if(field.wrapper!="")
                                    {
												
                                        aInfoFieldLink.href = "javascript:"+field.wrapper.replace("%s","\""+data[i].fields[j].value+"\"");
												
                                    }
                                }
                                aInfoFieldLink.target = (field!=null) ? field.target : "_blank";
                                var txtLinkCaption = (field!=null) ? field.linkCaption : "link";
                                aInfoLinkCaption = document.createTextNode(txtLinkCaption);
                                aInfoFieldLink.appendChild(aInfoLinkCaption);
                                divInfoFieldValue.appendChild(aInfoFieldLink);
										
                            }
                            else
                            {
                                divInfoFieldValue.appendChild(document.createTextNode(data[i].fields[j].value));
                            }
		
                            tdInfoFieldValue.appendChild(divInfoFieldValue);
									
                            trInfoField.appendChild(tdInfoFieldTitle);
                            trInfoField.appendChild(tdInfoFieldValue);
									
                            tbodyInfo.appendChild(trInfoField);
                        }
								
                    }
                    var extent = data[i].extent.split(',');
                    if (extent.length == 4)
                    {
                        trInfoCenter = document.createElement("tr");
                        //trInfoCenter.valign = "bottom";
                        tdInfoCenter = document.createElement("td");
                        tdInfoCenter.colSpan = 2;
                        divInfoCenter = document.createElement("div");
                        divInfoCenter.className = "egvControlInfoDivCenterInMap";
                        var a  = document.createElement("a");
								
                        var textNode = document.createTextNode(eGV.Lang.translate("info_centerelement"));
                        a.appendChild(textNode);
                        divInfoCenter.appendChild(a);
                        //divInfoCenter.innerHTML = "<a href='javascript:void(0);' onclick = 'eGV.maps[0].zoomToExtent("+olExtent.toBBOX()+")'>"+eGV.Lang.translate("info_centerelement")+"</a>";
                        tdInfoCenter.appendChild(divInfoCenter);
                        trInfoCenter.appendChild(tdInfoCenter);
                        tbodyInfo.appendChild(trInfoCenter);
								
                        //register events
                        OpenLayers.Event.observe(divInfoCenter, "click", OpenLayers.Function.bindAsEventListener(this.centerMap,{
                            "extent":extent,
                            "map":this.map
                            }) );
                    }
                }
                tableInfo.appendChild(tbodyInfo);
						
                //sets news values
                divMain.appendChild(tableInfo);
                liElement.removeChild(liElement.firstChild);
                liElement.className = "egvControlInfoLoadedLi";
                liElement.appendChild(divMain);
            }
		           
        }
	          
        this.checkNothingFound();
    },
    centerMap: function(e)
    {
		
        var olExtent = new OpenLayers.Bounds(parseInt(this.extent[0]),parseInt(this.extent[1]),parseInt(this.extent[2]),parseInt(this.extent[3]));
        this.map.zoomToExtent(olExtent);
    /*
			if (e != null) {
	            OpenLayers.Event.stop(e);
	        }*/
    },
	
		
    clearInnerHTML: function(obj)
    {
        while(obj.firstChild) obj.removeChild(obj.firstChild);
    }
    ,
		 	
		
    checkNothingFound : function(){
        //ar
        var nothingFound = true;
        for (var i = 0, top = this.nothingFound.length; i < top; i++){
            if (this.nothingFound[i]!= 0){
                nothingFound = false;
            }
        }
        if (nothingFound == true || this.nothingFound.length == 0) {
            this.div.innerHTML = this.nothingFoundMessage;
            this.div.className = "egvControlInfoDiv";
        }
		
    },
		
    CLASS_NAME: "eGV.Control.Info"
});


