/* --------------------------------------------------------------
 * OTHER JAVASCRIPT FUNCTIONS FOR BDGA
 * -------------------------------------------------------------- */

/**
 * Method: sortByCityName
 * Sorts cities by their name
 *
 * Parameters:
 * a -
 * b -
 *
 * Returns:
 * {Array} sorted by city name
 */
function sortByCityName(a, b) {
    var x = a.cityName.toLowerCase();
    var y = b.cityName.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

/**
 * Method: setCities
 * Dinamically create a list of cities with their coordinates, ordered by 
 * their names.  When a city is selected, the map moves to its location.
 *
 * Parameters:
 * response - DescribeFeatureType response
 */
function setCities(response) {
    oText = new OpenLayers.Format.Text();
    oFeatures = oText.read(response.responseText);

    var aCities = new Array();

    // put the results in an array first to be able to sort it
    for (var key in oFeatures){
        var szValue = "";
        szValue += oFeatures[key].geometry.x;
        szValue += ",";
        szValue += oFeatures[key].geometry.y

        aCities[key] = {
          cityName: oFeatures[key].attributes['title'],
          lonlat: szValue
        };
    }

    // sort the array by city name
    aCities.sort(sortByCityName);

    // create on option per city and add it to the select element
    var oSelect=document.getElementById("zoomToCity");
    for (i=0; i<aCities.length; i++){
        var oOption = document.createElement('option');
        oOption.text=aCities[i]['cityName'];
        oOption.value=aCities[i]['lonlat'];
        try
        {
            oSelect.add(oOption,null); // standards compliant
        }     
        catch(ex)
        {
            oSelect.add(oOption); // IE only
        }
    }

    // Enable the list and remove the "wait" message
    oSelect.disabled = "";
    oSelect.remove(0);
}

/**
 * Method: zoomToCity
 * This function is called when an city is selected and will move the map
 * to its location using map.setCenter function.
 *
 * forceZoomChange is set to true to change the renderer left and top
 * each time we use this function.
 *
 * Parameters:
 * element - html option element of a select representing the city which has
 *           lon,lat as value.
 */
function zoomToCity(element){
    oMap.setCenter(
        new OpenLayers.LonLat.fromString(element.value), // lonlat
        oMap.getZoom(),                                  // zoom
        '',                                              // dragging
        true                                             // forceZoomChange
    );
    toggleCityShortcut("hide");
}

/**
 * Method: showMsg
 * Parse a message in a hidden html element and show it for a momment
 *
 * Parameters:
 * szErrMsg -    string               The message to show
 *
 * id -          string               The id of the html element where to show
 *                                    the message
 */
function showMsg(szMessage) {
    document.getElementById("message").innerHTML = szMessage;
    setTimeout(
        "document.getElementById('message').innerHTML = ''",2000);
}

/**
 * Method: popMap
 * Pop current map view in new window.  For MapServer layers only.
 */
function popMap() {
    window.open(
        oMap.getMapURL(),
        '_blank',
        'fullscreen=no'            
    );
}

/**
 * Method: getMapURL
 * Return a query string for the map with current visible layers
 *
 * Parameters:
 *
 * Returns:
 * {String} A string with the basic layer's url and map parameters 
 *          and also the passed-in bounds and appropriate tile size 
 *          specified as parameters and the current visible overlays.
 */
OpenLayers.Map.prototype.getMapURL = function () {
    var url = "";
    for (var i=0, len=this.layers.length; i<len; i++) {
        if (!this.layers[i].isVector && this.layers[i].params != null) {
            if (this.layers[i].isBaseLayer && this.layers[i].getVisibility()) {
                url += this.getBasicLayerURL(this.getExtent(), i);
            } else if(this.layers[i].inRange && this.layers[i].getVisibility()){
                url += "&layers=" + this.layers[i].params.layers;
            }
        }
    }
    url = url.replace(" ", "%20");

    return url;
}

/**
 * Method: getBasicLayerURL
 * Return a query string for the map's basic layer
 *
 * Parameters:
 * bounds - {<OpenLayers.Bounds>} A bounds representing the bbox 
 *                                for the request
 * nLayer - integer               The position of the current basic
 *                                layer in the layer array
 *
 * Returns:
 * {String} A string with the basic layer's url and map parameters 
 *          and also the passed-in bounds and appropriate tile size 
 *          specified as parameters.
 */
OpenLayers.Map.prototype.getBasicLayerURL = function (bounds, nBasicLayer) {
    bounds = this.layers[nBasicLayer].adjustBounds(bounds);
    // Make a list, so that getFullRequestString uses literal "," 
    var extent = [bounds.left, bounds. bottom, bounds.right, bounds.top];

    var imageSize = this.getSize(); 
        
    // make lists, so that literal ','s are used 
    var url = this.layers[nBasicLayer].getFullRequestString(
                 {mapext:   extent,
                  imgext:   extent,
                  map_size: [imageSize.w, imageSize.h],
                  imgx:     imageSize.w / 2,
                  imgy:     imageSize.h / 2,
                  imgxy:    [imageSize.w, imageSize.h]
                  });
        
    return url;
}

function toggleCityShortcut(szToggle) {
    if(!szToggle || szToggle == "display"){
        szToggle = "";
    } else if (szToggle == "hide"){
        szToggle = "none";
    }
    var oCityShortcut = document.getElementById("cityShortcut");
    if(oCityShortcut.style.display != szToggle){
        oCityShortcut.style.display = szToggle;
    }
}

