AdfRichUIPeer.createPeerClass(AdfRichUIPeer, "AdfDhtmlGeoMapPeer", false);
AdfPage.PAGE.getLookAndFeel().registerPeerConstructor(
  "oracle.dss.adf.geoMap.GeoMap",
  "AdfDhtmlGeoMapPeer");

// We need this class to workaround some issues with Firefox
// when using multiple XMLHttpRequest. 
/**
 * @export
 * @this {AdfDhtmlGeoMapPeer}
 */
function MapAJAXConnection(url, callback) {
    var m_call = callback;
    var m_url = url;
    var req = init();
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
        if (req.status == 200) {
          if (m_call) m_call(req.responseXML, req.responseText);
        } else {
           var valueArray = new Array();
           valueArray.push(m_url);
           var message = AdfDhtmlGeoMapPeer._messageFormat(AdfDhtmlGeoMapPeer._ERROR_MSG_26017, valueArray);
           AdfDhtmlGeoMapPeer._showErrorMessage(message);
           AdfPage.PAGE.__perfTimings(false,false,false, "MapViewer Connection Failed");
        }
      }};
            
    function init() {    
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    

    this.doGet = function() {
      try {
          req.open("GET", m_url, true);
          req.send(null);
      } catch (e) {
          var valueArray = new Array();
          valueArray.push(m_url);
          var message = AdfDhtmlGeoMapPeer._messageFormat(AdfDhtmlGeoMapPeer._ERROR_MSG_26017, valueArray);
          AdfDhtmlGeoMapPeer._showErrorMessage(message);      
      }
    }
    
    this.doPost = function(body) {
      req.open("POST", m_url, true);
      req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      req.send(body);
    }
}

//TODO: Derive from javax.faces.SEPARATOR_CHAR context param in JSF 2
AdfDhtmlGeoMapPeer.NAMING_SEPARATOR = ":";

AdfDhtmlGeoMapPeer._formatMessage = function (num) 
{
    var sNum = num.toString();
    var decIndex = sNum.indexOf('.');
    var decPlaces = 0;
    if(decIndex != -1){
        decPlaces = sNum.length - (decIndex + 1);
    }
    
    var fixNum = Math.abs(num);
    fixNum = fixNum.toFixed(decPlaces);
    
    var factor = 1;
    for (var i=0; i < AdfDhtmlGeoMapPeer.GROUP_SIZE; i++)
    {
        factor = factor * 10;
    }   
    var result = "";

    var curFactor = factor;
    while (curFactor < fixNum)
    {
        if (curFactor * factor >= fixNum)
            break;
        else
            curFactor = curFactor * factor;
    }   
    
    while (curFactor > 1 && fixNum >= curFactor) 
    {
        var myDivisor = Math.floor(fixNum / curFactor);
        fixNum = fixNum - (myDivisor * curFactor);
        if (myDivisor > 0)
        {
            var myResult = myDivisor.toString();
            if (result.length > 0)
            {
                var diff = AdfDhtmlGeoMapPeer.GROUP_SIZE - myResult.length;
                for (i=0; i < diff; i++)
                {
                     myResult = "0" + myResult;                
                }
            }
            
            result = result + myResult + AdfDhtmlGeoMapPeer.GROUP_SEPARATOR;
        } 
        
        curFactor = curFactor / factor;
    }

    if (fixNum > 0)        
    {
        myResult = Math.floor(fixNum).toString();
        if (result.length > 0)
        {
            diff = AdfDhtmlGeoMapPeer.GROUP_SIZE - myResult.length;
            for (i=0; i < diff; i++)
            {
                myResult = "0" + myResult;                
            }
        }
    
        result = result + myResult;
    }       

    var remainder = fixNum - Math.floor(fixNum);
    if (remainder != 0)
    {
        var strNum = fixNum.toString();
        var dotIndex = strNum.indexOf('.') + 1;
        result += AdfDhtmlGeoMapPeer.DECIMAL_SEPARATOR + strNum.substr(dotIndex);
    }

    if (num < 0)    
        result = '-' + result;
        
    return result;
}

AdfDhtmlGeoMapPeer._showErrorMessage = function (msg) 
{
    AdfPage.PAGE.clearAllMessages();
    AdfPage.PAGE.addMessage(null, new AdfFacesMessage(AdfFacesMessage.TYPE_ERROR, 'Error', msg));
    AdfPage.PAGE.showMessages();    
}

AdfDhtmlGeoMapPeer._messageFormat = function (message, valueArray) {
    var result = message;
    
    if (valueArray == 0)
        return result;
        
    for (var i=0; i < valueArray.length; i++)    
    {
        var token = "{" + i.toString() + "}";
        result = result.replace (token, valueArray[0]);
    }
    
    return result;
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer._updateLegendValue = function (evt) 
{    
    var selOneChoice = evt.getSource();
    if (selOneChoice.getProperty('themeIds') == null) 
        return;

    var themeIds = selOneChoice.getProperty('themeIds').split(' ');    
    var choice = parseInt (evt.getNewValue());
    var oldChoice = parseInt (evt.getOldValue());
    
    var oldTableId = themeIds[oldChoice];
    var newTableId = themeIds[choice];
        
    var oldTable = document.getElementById(oldTableId);
    var newTable = document.getElementById(newTableId);
    
    if (newTable != null)
        newTable.style.display='block';
        
    if (oldTable != null)
        oldTable.style.display='none';
}

AdfDhtmlGeoMapPeer._parseThemeStyleResponse = function (image, dataSourceName, responseXML, mapServerURL) 
{
    var geocodeNode = responseXML.getElementsByTagName('theme_style');                        
    var styleName = null;

    image.onerror = null;
    
    for (var i=0; i < geocodeNode.length; i++)
    {
        if (geocodeNode[i].getAttribute('render') == 'true')
        {
            styleName = geocodeNode[i].getAttribute('name');
            break;
        }
    }
        
    if (styleName != null)
    {
        var mapRequest = mapServerURL + "?xml_request=";
        mapRequest += "<map_request datasource = \"" + dataSourceName + "\" format=\"PNG_STREAM\">";
        mapRequest += "<legend profile=\"MEDIUM\" position=\"SOUTH_EAST\">";
        mapRequest += "<column>";
        mapRequest += "<entry style=\"" + styleName + "\" tab=\"1\" />";
        mapRequest += "</column>";
        mapRequest += "</legend>";
        mapRequest += "</map_request>";        
    
        image.src = mapRequest;
    }
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer._getThemeLegendImage = function (image, mapId, dataSource, themeName, mapServerURL, contextPath) 
{    
    var mapRequestURL = "<?xml version=\"1.0\" standalone=\"yes\"?>";
    mapRequestURL += "<non_map_request>";
    mapRequestURL += "<list_theme_styles data_source=\"" + dataSource + "\" theme=\"" + themeName + "\"/>";
    mapRequestURL += "</non_map_request>";
    var encodeRequest = encodeURI(mapRequestURL);

    mapServerURL = mapServerURL + "/omserver";

    var adfMap = AdfPage.PAGE.findComponent(mapId);    
    var proxyPath = adfMap._getStyleElement().getAttribute('proxyPath');                 
    var param = "rtarget=" + mapServerURL + "&xml_request=" + encodeRequest;
    
    var customCallback = function (responseXML, responseText) {
        AdfDhtmlGeoMapPeer._parseThemeStyleResponse(image, dataSource, responseXML, mapServerURL);            
    }
        
    var connection = new MapAJAXConnection(proxyPath, customCallback);
    connection.doPost(param);    
}

AdfDhtmlGeoMapPeer._convertThemeToArray = function (activeTheme, selectTheme) 
{
    var hashTable = new Array();
    if (activeTheme.getFOIData() != null)
        for (i =0; i < activeTheme.getFOIData().length; i++)
            hashTable[activeTheme.getFOIData()[i]['id']] = activeTheme.getFOIData()[i];
    
    var prop = new Array();
    prop['selectionMode'] = 'Select';    
    
    if (selectTheme.getFOIData() != null)
    {
        for (i=0; i < selectTheme.getFOIData().length; i++)
        {       
            var selFOI = hashTable[selectTheme.getFOIData()[i]['id']];
            if (selectTheme.getFOIData()[i]['name'] == null)
                continue;
                
            if (selFOI != null)
            {
                AdfDhtmlGeoMapPeer._addFOIPropertyToArray(prop, selFOI);
            } else 
            {
                prop.push(selectTheme.getFOIData()[i]['name']);
                prop.push("");                
            }
        }
    }
    
    return prop;    
}

/**
 * @export
 * @this {AdfDhtmlGeoMapPeer}
 */
AdfDhtmlGeoMapPeer._selectThemeRefresh = function () 
{
    var mapId = this['parent']._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);                     

    var activeTheme = adfMap.getTheme(adfMap.getActiveTheme());
    var prop = AdfDhtmlGeoMapPeer._convertThemeToArray (activeTheme, this);

    adfMap._initMapTool();
    
    var event = new AdfMapSelectEvent(adfMap, prop);
    event.setPartial(true);
    adfMap.queueEvent(event);               

    this.setEventListener('after_refresh', null);
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer._getFOIFromTheme = function (adfMap, themeId, foiId) 
{    
    var selTheme = null;
    for (var i=0; i < adfMap._themeBasedFOIs.length; i++) {
        if (adfMap._themeBasedFOIs[i].getLayerName() == themeId) {
            selTheme = adfMap._themeBasedFOIs[i];
            break;
        }
    }
    
    var foiDatas = selTheme.getFOIData();
    for (i=0; i < foiDatas.length; i++) {
        if (foiDatas[i]['id'] == foiId)
            return foiDatas[i];
    }
    
    return null;
}

AdfDhtmlGeoMapPeer._fixHexString = function (str) 
{
    if (str.length == 1)
        return '0' + str;
    else
        return str;    
}

AdfDhtmlGeoMapPeer._getBorderColor = function (strColor) 
{
    var hRed = Math.floor(parseInt(strColor.substr(1, 2), 16) * 0.6);
    var hBlue = Math.floor(parseInt(strColor.substr(3, 2), 16) * 0.6);
    var hGreen = Math.floor(parseInt(strColor.substr(5, 2), 16) * 0.6);    
    return '#' + AdfDhtmlGeoMapPeer._fixHexString(hRed.toString(16)) + 
                 AdfDhtmlGeoMapPeer._fixHexString(hBlue.toString(16)) + 
                 AdfDhtmlGeoMapPeer._fixHexString(hGreen.toString(16));    
}

AdfDhtmlGeoMapPeer._isInfoWindowEvent = function (mouseEvent) {
    if (mouseEvent.relatedTarget != null)
    {
        var curNode = mouseEvent.relatedTarget;
        var insideInfoWindow = false;

        while (curNode != null)
        {
            if (curNode['id'] != null && (typeof curNode == 'string') &&
                curNode['id'].indexOf('mvinfodiv') >= 0)
            {
                insideInfoWindow = true;
                break;
            }
            curNode = curNode.parentNode;
        }

        if (insideInfoWindow)
        {
            return true;
        } 
        
    } 
 
    return false;    
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer._attachHandler = function (point, foi, mouseEvent) {
    if (!AdfDhtmlGeoMapPeer._isInfoWindowEvent(mouseEvent))
    {
        if (mouseEvent.type== 'mouseover')
        {
            AdfDhtmlGeoMapPeer._showInfoWindow (foi.getGeometry(), foi, mouseEvent); 
        }

        foi.setEventListener('mouse_over', AdfDhtmlGeoMapPeer._showInfoWindow);
        foi.setEventListener('mouse_out', null);        
    } 
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer._showInfoWindow = function(point, foi, mouseEvent, adfMap, skipCallback, nsdpThemeId) 
{            
    if (adfMap == null) 
    {
        var mapId = foi['parent']._mvMapViewId;    
        adfMap = AdfPage.PAGE.findComponent(mapId);                             
    }

    adfMap.getMVMapView().removeInfoWindow();

    var themeId = null;
    var rowId = null;
        
    if (foi['_themeID'] != null)
    {
        themeId = foi['_themeID'];
        rowId = foi.getId();
        rowId = rowId.substring(themeId.length + 1);
    } else
    {
        themeId = nsdpThemeId;
        var attributeNames = foi['attrnames'];
        
        if (attributeNames != null)
        {    
            for (i=0; i < attributeNames.length; i++)
            {                
                if (attributeNames[i] == '__adf_rowId')
                {
                    rowId = foi['attrs'][i];
                    break;
                }
            }
        }                             
    }
    
    if (adfMap.getMapTool() == 'hand')
    {
        if (AdfDhtmlGeoMapPeer._findThemeInfo(adfMap._themeInfoTable, themeId, 'hasCallback') && 
            skipCallback == null) 
        {            
            var event = new AdfMapInfoWindowEvent(adfMap, rowId, themeId, foi.getId());
            event.setPartial(true);
            adfMap.queueEvent(event);                        
        } else 
        {        
            var infoWindowTableClass = adfMap._getStyleElement().getAttribute('infoWindowTableClass');        
            var htmlString = "<table cellspacing='0' cellpadding='0' class='" + infoWindowTableClass + "'";
            if (AdfAgent.getAgent().getPlatform() == AdfAgent.IE_PLATFORM)     
            {
                htmlString += " style='word-break:break-all'";
            }
            htmlString + ">";
            var attributeNames = foi['attrnames'];
            var attributeValues = foi['attrs'];
            if (attributeValues == null)
                return;

            if (mouseEvent != null && mouseEvent.type== 'mouseover' && foi['_themeID'] != null) {
                foi.setEventListener("mouse_over", AdfDhtmlGeoMapPeer._attachHandler);
            }

            var label = new Array();
            var value = new Array();
            var locationLabel = foi['name'];
            
            if (attributeNames != null)
            {
                for (i=0; i < attributeNames.length; i++)
                {                                
                    if (attributeNames[i] != '__adf_Location' &&
                        attributeNames[i] != '__adf_rowId' &&
                        attributeNames[i] != '__adf_location_label' &&                    
                        attributeNames[i].indexOf('__adf_item_Label') != 0)
                    {      
                        if (attributeNames[i].indexOf('__adf_empty_Label') == 0) {
                            label.push('&nbsp;');
                        } else {
                            label.push(attributeNames[i]);
                        }
                    }  else if (attributeNames[i].indexOf('__adf_item_Label') == 0) {
                        value.push(attributeValues[i]);
                    } else if (attributeNames[i].indexOf('__adf_location_label') == 0) {
                        locationLabel = attributeValues[i];
                    }
                }
            }     
            
            var dataLabelArray = null;
            var valueArray = null;
            
            if (rowId == null) 
            {
                dataLabelArray = attributeNames;
                valueArray = attributeValues;
            } else {
                dataLabelArray = label;
                valueArray = value;
            }
            
            var themeElem = adfMap._getThemeDefinitionElement(themeId);
            var colors = null;
            var themeType = themeElem.getAttribute('themeType');
            var isBidi = AdfPage.PAGE.getLocaleContext().isRightToLeft();
            
            if (themeType != null )
            {            
                if (themeType == 'BarChartTheme' || themeType == 'PieChartTheme') 
                {
                    var shortLabel = themeElem.getAttribute('shortLabel');
                    if (shortLabel != null)
                    {
                        htmlString += "<tr><td colspan=3><b>" + shortLabel + "</b></td></tr>";
                        htmlString += "<tr><td colspan=3 height='5'></td></tr>";                
                    }
                    
                    if (themeType == 'BarChartTheme')       
                    {
                        colors = themeElem.getAttribute('barColors').split(';');                        
                    } else if (themeType == 'PieChartTheme') 
                    {
                        colors = themeElem.getAttribute('sliceColor').split(';');                
                    }
                }
            }
                        
            for (i=0; i < dataLabelArray.length; i++)
            {
                var dataLabel = dataLabelArray[i];
                
                if (typeof dataLabel == 'undefined' || dataLabel == null)
                    dataLabel = '&nbsp;';

                if (i > 0)                    
                    htmlString += "<tr><td colspan='3' height='5'></td></tr>";
                    
                htmlString+= "<tr>";
                if (colors != null)
                {
                    borderColor = AdfDhtmlGeoMapPeer._getBorderColor(colors[i]);
                    var margin = "margin-right:";
                    if(isBidi)
                        margin = "margin-left:";
                        
                    htmlString += "<td style='width:12px'><div style='width:10px;height:10px;" + margin + "3px;background-color:" + colors[i] + ";border:1px solid " + borderColor + "'>&nbsp;</div></td>";
                }
                
                var padding = "padding-left:";
                if(isBidi)
                    padding = "padding-right:";
                    
                htmlString += "<td nowrap><span style='color:#534741;'>" + dataLabel + "</span></td><td><span style='" + padding + "8px'>" + valueArray[i] + "</span></td></tr>";                      
            }
            
            htmlString += "</table>"; 
        
            var infoWindowLocation = point;
            if (mouseEvent != null && mouseEvent.type== 'mouseover' && foi['_themeID'] != null) {
                infoWindowLocation = foi.getGeometry();
                foi.setEventListener('mouse_out', AdfDhtmlGeoMapPeer._attachHandler);                
            }

            var infoWindowTitleClass = adfMap._getStyleElement().getAttribute('infoWindowTitleClass');
            var titleString = "<div class='" + infoWindowTitleClass + "'";
            if (AdfAgent.getAgent().getPlatform() == AdfAgent.IE_PLATFORM)     
            {
                titleString += " style='text-wrap:none'";
            }

            titleString += ">" + locationLabel + "</div>";            
            adfMap.getMVMapView().displayInfoWindow(infoWindowLocation, htmlString, null, null, null, titleString);            
        }
    }
}

AdfDhtmlGeoMapPeer._getThemeInfoIndex = function(themeInfoTable, themeId) 
{
    for (var i=0; i < themeInfoTable.length; i++)
    {
        if (themeInfoTable[i]['id'] == themeId)
        {
            return i;
        }
    }    
    
    return -1;
}

AdfDhtmlGeoMapPeer._findThemeInfo = function (themeInfoTable, themeId, key)
{
    for (var i=0; i < themeInfoTable.length; i++)
    {
        if (themeInfoTable[i]['id'] == themeId)
        {
            if (themeInfoTable[i][key] != null)
                return true;
        }
    }
    
    return false;
}

AdfDhtmlGeoMapPeer._getThemeInfoValue = function (themeInfoTable, themeId, key)
{
    for (var i=0; i < themeInfoTable.length; i++)
    {
        if (themeInfoTable[i]['id'] == themeId)
        {
            if (themeInfoTable[i][key] != null)
                return themeInfoTable[i][key];
        }
    }
    
    return null;
}

AdfDhtmlGeoMapPeer._addFOIPropertyToArray = function (prop, foi) 
{
    if (foi['_themeID'] != null)
    {
        themeId = foi['_themeID'];
        rowId = foi['id'];
        rowId = rowId.substring(themeId.length + 1);
        prop.push (foi['name']);
        prop.push (rowId);                        
        prop.push (foi.getGeometry().getPointX());
        prop.push (foi.getGeometry().getPointY());    
        prop.push (foi._category);
        prop.push (foi['attrnames'][0]);
        if (foi['attrs'] == null)
        {
            prop.push ('');                                                
            prop.push ('');
        } else
        {
            prop.push (foi['attrs'][0]);                                                
            prop.push (foi['attrs'][1]);
        }
    } else 
    {
        var attributeNames = foi['attrnames'];
        var attributeValues = foi['attrs'];
                        
        var label = new Array();
        var value = new Array();
        var unFormat = new Array();
        var rowId = null;
        var locationName = null;
        var locationLabel = null;
            
        if (attributeNames != null)
        {
            for (j=0; j < attributeNames.length; j++)
            {                                
                if (attributeNames[j] != '__adf_Location' &&
                    attributeNames[j] != '__adf_rowId' &&
                    attributeNames[j] != '__adf_location_label' &&
                    attributeNames[j].indexOf('__adf_item_Label') != 0)
                {                        
                    label.push(attributeNames[j]);
                    if (attributeValues == null || attributeValues[j] == null)
                        unFormat.push('');
                    else
                        unFormat.push(attributeValues[j]);
                } else if (attributeNames[j].indexOf('__adf_item_Label') == 0) {
                    value.push(attributeValues[j]);
                } else if (attributeNames[j] == '__adf_rowId') {
                    rowId = attributeValues[j];
                } else if (attributeNames[j] == '__adf_Location') {
                    if (attributeValues == null || attributeValues[j] == null)
                        locationName = '';
                    else
                        locationName = attributeValues[j];
                } else if (attributeNames[j] == '__adf_location_label') {
                    if (attributeValues == null || attributeValues[j] == null)
                        locationLabel = '';
                    else
                        locationLabel = attributeValues[j];
                }
            }
        }     

        if (rowId != null)
        {
            prop.push(locationName);            
            prop.push(rowId);
            prop.push(locationLabel);
            prop.push(label.length);
        
            for (j=0; j < label.length; j++)
            {
                prop.push(label[j]);
                prop.push(unFormat[j]);
                prop.push(value[j]);
            }             
        } else {
            prop.push(foi['name']);
            prop.push(foi['id']);
            if (attributeNames == null)
            {
                prop.push('0');
            } else
            {
                prop.push(attributeNames.length);
                for (j=0; j < attributeNames.length; j++)
                {
                    prop.push(attributeNames[j]);
                    if (attributeValues == null || attributeValues[j] == null)
                        prop.push('');
                    else         
                        prop.push(attributeValues[j]);
                }
            }                 
        }
    }    
}

/**
 * @export
 * @this {AdfDhtmlGeoMapPeer}
 */
AdfDhtmlGeoMapPeer._FOIClick = function(point, foi, mouseEvent)
{                
    var mapId = this['parent']._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);   
    var mapTool = adfMap.getMapTool();

    var themeId = null;
        
    if (typeof(this.getLayerName) == 'undefined')
    {
        themeId = this['_themeID'];
    } else
    {
        themeId = this.getLayerName();
    }        
    
    var action = null;
    
    if (mapTool == 'hand')
        action = 'click';
    else if (mapTool == 'pointSelection')
        action = 'selection';

    var mouseX = null;
    var mouseY = null;
    var buttonClick = "left";

    if (mouseEvent.pageX) 
    {
        if (mouseEvent.button == 0)
            buttonClick = "left";
        else if (mouseEvent.button == 2)
            buttonClick = "right";
                
        mouseX = mouseEvent.pageX;
        mouseY = mouseEvent.pageY;                    
    } else 
    {
        if (mouseEvent.button == 1)
            buttonClick = "left";
        else if (mouseEvent.button == 0)
            buttonClick = "right";
        
        mouseX = mouseEvent.clientX;
        mouseY = mouseEvent.clientY;                    
    }        
    
    adfMap.getPeer()._clickFOI(foi, point, action, themeId, mouseX, mouseY, mouseEvent, buttonClick);    
}

AdfDhtmlGeoMapPeer.prototype._clickFOI = function (foi, point, action, themeId, mouseX, mouseY, mouseEvent, buttonClick)
{
    var adfMap = this.getComponent();                     
    var mapId = adfMap.getClientId();
    adfMap.getMVMapView().removeInfoWindow();

    if (action == 'click')
    {        
        adfMap._currentFOI = foi;
        adfMap._currentFOITheme = themeId;

        if (buttonClick == "left")
        {       
            var ltBehavior = AdfDhtmlGeoMapPeer._getThemeInfoValue(adfMap._themeInfoTable, themeId, 'leftClickBehavior');

            var popupId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "myPopup";
            var popup = AdfPage.PAGE.findComponent(popupId);
            if (popup != null)
                popup.hide();

            if (ltBehavior == 'FireEvent')            
            {               
                var props = new Array();
                AdfDhtmlGeoMapPeer._addFOIPropertyToArray(props, foi);
                var event = new AdfMapClickActionEvent(adfMap, props, themeId, foi['id'], "left", mouseX, mouseY, point);
                
                event.setPartial(true);
                adfMap.queueEvent(event);            
            } else if (ltBehavior == 'LaunchPopup') {
                var hints = new Array();
                hints[AdfDhtmlCommonUtils.MOUSEPOSITION] = {'x': mouseX, 'y': mouseY};            
                popup.show(hints);            
            } else if (ltBehavior == 'LaunchInfoWindow') {
                AdfDhtmlGeoMapPeer._showInfoWindow(point, foi, mouseEvent, adfMap, null, themeId);        
            }
        } else if (buttonClick == "right") 
        {        
            var rtBehavior = AdfDhtmlGeoMapPeer._getThemeInfoValue(adfMap._themeInfoTable, themeId, 'rightClickBehavior');

            var popupId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "rtPopup";
            var popup = AdfPage.PAGE.findComponent(popupId);
            if (popup != null)
                popup.hide();

            if (rtBehavior == 'FireEvent')            
            {                                       
                var props = new Array();            
                AdfDhtmlGeoMapPeer._addFOIPropertyToArray(props, foi);                
                var event = new AdfMapClickActionEvent(adfMap, props, themeId, foi['id'], "right", mouseX, mouseY, point);
                event.setPartial(true);
                adfMap.queueEvent(event);                            
            } else if (rtBehavior == 'LaunchPopup') {
                var hints = new Array();
                hints[AdfDhtmlCommonUtils.MOUSEPOSITION] = {x: mouseX, y: mouseY};            
                popup.show(hints);
            } 
        }
    } else if (action=='selection')
    {
        adfMap._currentFOI = foi;    
        var selectFOI = null;

        if (adfMap.getActiveTheme() == null)
            return;
        
        if (adfMap._selectTheme != null && adfMap._selectTheme.getFilteringGeom() == null) 
        {
           var selectFOIs = adfMap._selectTheme.getFOIData();
           if (selectFOIs != null && selectFOIs.length > 0)
               selectFOI = selectFOIs[0];
        }
        
        if (adfMap.getActiveTheme() == themeId)
        {                        
            adfMap._clearSelection();
            
            if (!(selectFOI != null && foi != null && selectFOI['name']== foi['name']))                    
                adfMap._toolFinishCallback(foi);        
        }
    }    
}

/**
 * @this {AdfDhtmlGeoMapPeer}
 */
AdfDhtmlGeoMapPeer._handleMouseMove = function (event) 
{
    var e = event;
    if (!e) 
        e = window.event;

    var x = e.clientX;
    var y = e.clientY;
        
    var mapId = this['id'];
    if (mapId == null)
        return;
        
    var adfMap = AdfPage.PAGE.findComponent(mapId);    
    if (adfMap == null || adfMap.getMVMapView() == null)
        return;

    var latElem = document.getElementById(mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "latitude");
    var longElem = document.getElementById(mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "longitude");
    
    if (latElem == null || longElem == null)
        return;

    if (latElem.style.display == 'none' || longElem.style.display == 'none')
        return;

    var currentTime = new Date();
    if (latElem._curMinute != null && latElem._curSecond != null && latElem._curMilliSeconds != null) 
    {
        if (latElem._curMinute == currentTime.getMinutes() && 
            latElem._curSecond == currentTime.getSeconds())
        {
            if ((currentTime.getMilliseconds() - latElem._curMilliSeconds) < 200)
                return;
        }
    }
    
    var srid = adfMap.getMVMapView().srid;        
    var mouseLocation = MVUtil.getMouseLocation(adfMap.getMVMapView(), e);        
    mouseLocation.srid = srid;
    if (srid == 54004)
    {
        latElem._curMinute = currentTime.getMinutes();
        latElem._curSecond = currentTime.getSeconds();
        latElem._curMilliSeconds = currentTime.getMilliseconds();        
        mouseLocation = adfMap.getMVMapView().transformGeom(mouseLocation, 8307);
    }
    
    var longX = mouseLocation.getPointX();
    var latY = mouseLocation.getPointY();

    var xLabel = AdfDhtmlGeoMapPeer._X + ":";                  
    var yLabel = AdfDhtmlGeoMapPeer._Y + ":";
              
    if (srid == 8307 || srid == 54004)
    {
        xLabel = AdfDhtmlGeoMapPeer._LONGITUDE + ":";
        yLabel = AdfDhtmlGeoMapPeer._LATITUDE + ":";
    }
    
    var infoImagePath = adfMap._getStyleElement().getAttribute('INFO_IMAGE_PATH');

    latElem.innerHTML = "<img src='" + infoImagePath + "' align='top' style='margin-top:1px;margin-right:4px;vertical-align:text-top'/>"+ yLabel + "&nbsp;<font color='#FFFFFF'>" + AdfDhtmlGeoMapPeer._formatMessage(latY.toFixed(4)) + "</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    longElem.innerHTML = xLabel + "&nbsp;<font color='#FFFFFF'>" + AdfDhtmlGeoMapPeer._formatMessage(longX.toFixed(4)) + "</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";    
}

AdfDhtmlGeoMapPeer._generateErrorMessage = function (addressNode, themeId, row) {
    var errMsg = "Unable to find a match for row (" + row + ") for Theme '" + themeId + "':\n";
    var childNode = addressNode.childNodes[0];
    for (var i=0; i < childNode.attributes.length; i++)   {
        if (i != 0)
            errMsg += ", ";
        errMsg += childNode.attributes[i].nodeName + "=" + childNode.attributes[i].nodeValue;
    }
    
    errMsg += "\n";
    return errMsg;
}

AdfDhtmlGeoMapPeer._getDomParser = function () {
    if (typeof DOMParser == "undefined") {
        DOMParser = function () {}

        DOMParser.prototype.parseFromString = function (str, contentType) {
            if (typeof ActiveXObject != "undefined") {
                var d = new ActiveXObject("MSXML.DomDocument");
                d.loadXML(str);
                return d;
            } else if (typeof XMLHttpRequest != "undefined") {
                var req = new XMLHttpRequest;
                req.open("GET", "data:" + (contentType || "application/xml") +
                                ";charset=utf-8," + encodeURIComponent(str), false);
                if (req.overrideMimeType) {
                    req.overrideMimeType(contentType);
                }

                req.send(null);
                return req.responseXML;
            }
        }
     } 

     return (new DOMParser());
}

AdfDhtmlGeoMapPeer._getXMLHttpRequest = function () {
    req = false;
    if(window.XMLHttpRequest && !(window.ActiveXObject)) 
    {
    	try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
    } else if(window.ActiveXObject) {
       	try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
      	} catch(e) {
            req = false;
        }
    }
    
    return req;    
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer._parseGeocodeResponse = function (responseXML, mapId, themeId, zoomMode, matchMode, geocodeRequest, geocoderURL) {

    var requestNode = AdfDhtmlGeoMapPeer._getDomParser().parseFromString(geocodeRequest, "text/xml");
    var allAddresses = requestNode.getElementsByTagName('input_address');    
        
    if (responseXML == null)
    {
        var valueArray = new Array();
        valueArray.push(geocoderURL);
        var message = AdfDhtmlGeoMapPeer._messageFormat(AdfDhtmlGeoMapPeer._ERROR_MSG_26018, valueArray);
        AdfDhtmlGeoMapPeer._showErrorMessage(message);    
        return;
    }
    
    var adfMap = AdfPage.PAGE.findComponent(mapId);
    var minX = null;
    var minY = null;
    var maxX = null;
    var maxY = null;

    var errMessage = null;
    var errIndex = null;
    
    if (adfMap != null && adfMap._foiTheme[themeId] != null)
    {        
        var geocodeNode = responseXML.getElementsByTagName('geocode');        
        for (var i=0; i < geocodeNode.length; i++)
        {            
            var foi = adfMap._foiTheme[themeId][i];                                          
            
            var matchNode = geocodeNode[i].getElementsByTagName('match');
            if (matchNode == null || matchNode.length < 1)
            {
                if (errMessage == null)
                {
                    errMessage = AdfDhtmlGeoMapPeer._generateErrorMessage(allAddresses[i], themeId, i);
                    errIndex = i.toString();
                } else
                {
                    errMessage += "\n" + AdfDhtmlGeoMapPeer._generateErrorMessage(allAddresses[i], themeId, i);
                    errIndex += ";" + i.toString();
                }
                
                foi['parent'] = null;        
                continue;            
            }
            
            var matchcode = matchNode[0].getAttribute('match_code');            
            
            if (matchMode == 'exact' && matchcode != '1')
            {
                if (errMessage == null)
                {
                    errMessage = AdfDhtmlGeoMapPeer._generateErrorMessage(allAddresses[i], themeId, i);
                    errIndex = i.toString();
                } else
                {
                    errMessage += "\n" + AdfDhtmlGeoMapPeer._generateErrorMessage(allAddresses[i], themeId, i);
                    errIndex += ";" + i.toString();
                }            
            
                foi['parent'] = null;        
                continue;
            }            

            var latitude = parseFloat(matchNode[0].getAttribute('latitude'));

            if (minY == null || minY > latitude)
                minY = latitude;
            if (maxY == null || maxY < latitude)
                maxY = latitude;

            var longitude = parseFloat(matchNode[0].getAttribute('longitude'));
            
            if (minX == null || minY > longitude)
                minX = longitude;
            if (maxX == null || maxY < longitude)
                maxX = longitude;

            var point = MVSdoGeometry.createPoint(longitude, latitude, 8307);
            foi.updateGeometry(point);          
            if (foi.node != null)
            {  
                foi.setVisible(true);            
            }

            foi.reDraw();
        }
    }

    if (errMessage != null)
    {
        var event = new AdfGeocodeEvent(adfMap, themeId, errIndex);
        event.setPartial(true);
        adfMap.queueEvent(event);               
    
        AdfLogger.LOGGER.logError(adfMap, AdfLogger.SEVERE, errMessage);
    }
    
    for (i=0; i < adfMap._themeInfoTable.length; i++)    
        if (adfMap._themeInfoTable[i]['id'] == themeId)
            adfMap._themeInfoTable[i]['loaded'] = true;                        

    if (zoomMode != 'none')
    {
        if (minX != null && minY != null && maxX != null && maxY != null)
        {
            if (zoomMode == 'zoom')
            {
                adfMap.getMVMapView().zoomToRectangle(MVSdoGeometry.createRectangle(minX, minY, maxX, maxY, 8307));                    
            } else if (zoomMode == 'centerOnly')
            {
                var centerX = (minX + maxX) / 2.0;
                var centerY = (minY + maxY) / 2.0;
                adfMap.getMVMapView().setCenter(MVSdoGeometry.createPoint (centerX, centerY, 8307));
            }            
        }
    }
}

AdfDhtmlGeoMapPeer._adjustInfoWindowWidth = function (mapId, newWidth) 
{
    var longId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + 'longitude';
    var langId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + 'latitude';
    var latlongId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + 'latlong';
    var distAreaElemId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "distanceArea"; 
    
    var latlongEndId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "longlatEnd";
    var latlongConnectorId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "longlatConnector";
    var distAreaStartId = mapId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "distanceAreaStart";
    
    var distanceAreaElem = document.getElementById(distAreaElemId);            
    var longElem = document.getElementById(longId);
    var langElem = document.getElementById(langId);
    var latlongElem = document.getElementById(latlongId);
    var latlongEndElem = document.getElementById(latlongEndId);
    var latlongConnectorElem = document.getElementById(latlongConnectorId);
    var distAreaStartElem = document.getElementById(distAreaStartId);
    
    var mapWidth;

    if (newWidth != null)
    {
        mapWidth = newWidth;
    } else
    {
        var mapDomElement = document.getElementById(AdfRichUIPeer.CreateSubId(mapId, "actualMap"));
        mapWidth = parseInt(mapDomElement.style.width);                         
    }

    var boxWidth = mapWidth - 50;    
    var elemWidth = Math.ceil(boxWidth / 3);

    if (distanceAreaElem != null && latlongElem != null)    
    {
        if (distanceAreaElem.innerHTML.length > 0 && latlongElem.style.display != 'none')
        {        
            if (elemWidth <= 100)
            {
                longElem.style.width = elemWidth.toString() + "px";
                langElem.style.width = elemWidth.toString() + "px";            

                var latlongWidth = elemWidth * 2;
                latlongElem.style.width = latlongWidth.toString() + "px";
                distanceAreaElem.style.width = elemWidth.toString() + "px";            
            } else {
                longElem.style.width = AdfDhtmlGeoMapPeer._longWidth.toString() + "px";
                langElem.style.width = AdfDhtmlGeoMapPeer._latWidth.toString() + "px";
                latlongElem.style.width = null;
                distanceAreaElem.style.width = null;  
                latlongEndElem.style.display="none";
                latlongConnectorElem.style.display = "block";
                distAreaStartElem.style.display = "none";
            }
       } else if (distanceAreaElem.innerHTML.length > 0) {
            distanceAreaElem.style.width = null;          
            distAreaStartElem.style.display = "block";
       } else if (latlongElem.style.display != 'none') {
            elemWidth = Math.ceil(boxWidth / 2);

            if (elemWidth <= 100)
            {
                longElem.style.width = elemWidth.toString() + "px";
                langElem.style.width = elemWidth.toString() + "px";            
                latlongElem.style.width = boxWidth.toString() + "px";
            } else {
                longElem.style.width = AdfDhtmlGeoMapPeer._longWidth.toString() + "px";
                langElem.style.width = AdfDhtmlGeoMapPeer._latWidth.toString() + "px";
                latlongElem.style.width = null;
                latlongEndElem.style.display="block";
                latlongConnectorElem.style.display="none";
            }
        }                        
    
        if (latlongElem.style.display == 'none')
        {
            latlongEndElem.style.display="none";
            latlongConnectorElem.style.display="none";
        }
    
        if (distanceAreaElem.innerHTML.length == 0)
        {
            distanceAreaElem.style.width = "0px";
            latlongConnectorElem.style.display = "none";
            distAreaStartElem.style.display="none";
        }             
    }    
}

/**
 * @export
 */
AdfDhtmlGeoMap._selectMapType = function (elem) 
{
    var idList = elem['id'].split(AdfRichUIPeer.createSubId("", "")); //createSubId("","") returns subid separator
    var mapId = idList[0];
    var baseMapId = idList[1];
 
    var mapStyleElem = document.getElementById(AdfRichUIPeer.CreateSubId(mapId, "mapStyle"));            
    var mapElem = document.getElementById(AdfRichUIPeer.CreateSubId(mapId, "mapSwitch"));
    var satelliteMapElem = document.getElementById (AdfRichUIPeer.CreateSubId(mapId, "satelliteMapSwitch"));
    var hybridMapElem = document.getElementById (AdfRichUIPeer.CreateSubId(mapId, "hybridMapSwitch"));

    var mapControlClass = mapStyleElem.getAttribute('mapControlStyleClass');      
    var mapControlNotSelectClass = mapStyleElem.getAttribute('mapControlStyleClassNotSelect');                
     
    var adfMap = AdfPage.PAGE.findComponent(mapId);                         
    if (baseMapId == "mapSwitch") 
    {
        adfMap._baseMap.setVisible(true);    
                
        if (adfMap._satelliteMap != null)
            adfMap._satelliteMap.setVisible(false);
            
        if (adfMap._hybridMap != null)
            adfMap._hybridMap.setVisible(false);

        if (mapElem != null)
            mapElem.className = mapControlClass;        
        
        if (satelliteMapElem != null)
            satelliteMapElem.className = mapControlNotSelectClass;
            
        if (hybridMapElem != null)
            hybridMapElem.className = mapControlNotSelectClass;
    } else if (baseMapId == "satelliteMapSwitch") {
        adfMap._baseMap.setVisible(false);    
        
        if (adfMap._satelliteMap != null)
            adfMap._satelliteMap.setVisible(true);
            
        if (adfMap._hybridMap != null)
            adfMap._hybridMap.setVisible(false);           

        if (mapElem != null)
           mapElem.className = mapControlNotSelectClass;        
           
        if (satelliteMapElem != null)        
           satelliteMapElem.className = mapControlClass;
        
        if (hybridMapElem != null)        
            hybridMapElem.className = mapControlNotSelectClass;            
    } else if (baseMapId == "hybridMapSwitch") {
        adfMap._baseMap.setVisible(false);    
        
        if (adfMap._satelliteMap != null)
            adfMap._satelliteMap.setVisible(true);
            
        if (adfMap._hybridMap != null)
            adfMap._hybridMap.setVisible(true);        

        if (mapElem != null)
            mapElem.className = mapControlNotSelectClass;        
            
        if (satelliteMapElem != null)        
            satelliteMapElem.className = mapControlNotSelectClass;
            
        if (hybridMapElem != null)        
            hybridMapElem.className = mapControlClass;            
    }
}

AdfDhtmlGeoMapPeer.prototype._getDataSourceName = function() {
    var domElement = this.getDomElement();
    var mapId = domElement['id'];

    var mapStyleElem = document.getElementById(AdfRichUIPeer.CreateSubId(mapId, "mapStyle"));               
    var baseMapName = mapStyleElem.getAttribute('baseMapName').split('.');
    return baseMapName[0];
}

/**
 * @this {MVMapView}
 */
AdfDhtmlGeoMapPeer.prototype._doubleClick = function(event) 
{    
    var mapId = this._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);                     

    if (adfMap.getMapTool() == 'hand')
    {
        this.zoomIn(this.getMouseLocation());
    }     
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer.prototype._MapClick = function(event)
{
    var mapId = this._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);                     

    if (adfMap.getMapTool() == 'zoomIn')
    {
        this.zoomIn(this.getMouseLocation());
    } else if (adfMap.getMapTool() == 'zoomOut') {
        if (this.getZoomLevel() > 0)
        {
            this.zoomOut(this.getMouseLocation());
        }
    } else if (adfMap.getMapTool() == 'pointSelection') {
        if (adfMap.getActiveTheme() == null)
            return;

        var activeTheme = adfMap.getMVMapView().getThemeBasedFOI(adfMap.getActiveTheme());                

        if (activeTheme != null) {
            adfMap._clearSelection();
            adfMap._toolFinish();        
        }            
    } else if (adfMap.getMapTool() == 'hand') {    
        if (AdfAgent.getAgent().getPlatform() != AdfAgent.IE_PLATFORM)     
        {
//            var point = adfMap.getMVMapView().getMouseLocation();
//            var actionEvent = new AdfMapClickActionEvent(adfMap, new Array(), adfMap.getActiveTheme(), null, "left", //null, null, point);                        
//            actionEvent.setPartial(true);
//            adfMap.queueEvent(actionEvent);                            
        }
    } 

    if (AdfAgent.getAgent().getPlatform() != AdfAgent.IE_PLATFORM || document.createEvent)     
    {    
        var mouseEvent = document.createEvent('MouseEvents');
        mouseEvent.initMouseEvent('mousedown', true, true, window, 1.0, 
                                  event.screenX, event.screenY, event.clientX, event.clientY,
                                  event.ctrlKey, event.altKey, event.shiftKey,
                                  event.metaKey, event.button, event.relatedTarget
                                 );
        document.getElementById(mapId).dispatchEvent(mouseEvent);
    } else {
        var mapElem = document.getElementById(mapId);
        mapElem.fireEvent('onmousedown');
    }
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer.prototype._MapRTCancel = function()
{
    var mapId = this._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);                     

    if (adfMap.getMapTool() == 'ruler')
    {
        adfMap._displayDistanceArea(false, AdfDhtmlGeoMapPeer._DISTANCE, 0);
        adfMap._measureTool.clear();                
        adfMap._measureTool.init();        
    } else if (adfMap.getMapTool() == 'area') {
        adfMap._displayDistanceArea(false, AdfDhtmlGeoMapPeer._AREA, 0);                              
        adfMap._areaTool.clear();
        var oldFOI = this.getFOI('__adf_areaTool_Polygon');
        if (oldFOI != null)
        {
            this.removeFOI(oldFOI);
        }            

        adfMap._areaTool.init();                
    }
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer.prototype._recenterListener = function() 
{
    var mapId = this._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);    
    var styleElem = adfMap._getStyleElement();
    var startSRID = styleElem.getAttribute('startSRID');

    var newCenter = this.getCenter();
    if (newCenter.srid != startSRID) 
    {
        newCenter = this.transformGeom(this.getCenter(), startSRID);
    }
    
    var newX = newCenter.getPointX().toString();
    var newY = newCenter.getPointY().toString();
    var newSRID = newCenter.srid.toString();
    
    adfMap.setProperty('centerX', newX);
    adfMap.setProperty('centerY', newY);
    adfMap.setProperty('centerSrid', newSRID);

    var mapRecenterEvent = new AdfMapRecenterEvent(adfMap, newX, newY, newSRID);
    mapRecenterEvent.setPartial(true);
    adfMap.queueEvent(mapRecenterEvent);
}



// For Color and BarPieTheme Only
/**
 * @export
 */
AdfDhtmlGeoMapPeer.prototype._beforeZoomListener = function(oldZoomLevel, curZoomLevel)
{
    var mapId = this._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);               

    for (var i=0; i < adfMap._themeInfoTable.length; i++)
    {
        var themeEntry = adfMap._themeInfoTable[i];
        var isAlreadyVisible = adfMap._isThemeVisibleinZoomLevel (themeEntry, oldZoomLevel);
        var isNewlyVisible = adfMap._isThemeVisibleinZoomLevel (themeEntry, curZoomLevel);
        
        if (themeEntry['id'] == adfMap.getActiveTheme() && !isNewlyVisible) 
        {
            adfMap._clearSelection();    
        }
        
        if (isAlreadyVisible != isNewlyVisible)
        {
            if (themeEntry['toolbarVisible'] != null && 
                themeEntry['toolbarVisible'] == false &&
                isNewlyVisible)
                continue;

            if (themeEntry['type'] == 'PointTheme')
            {
                if (!isNewlyVisible || themeEntry['loaded'])                    
                    adfMap._setPointThemeVisible(themeEntry, isNewlyVisible);                                        
            } else
            {
                if (!isNewlyVisible || themeEntry['loaded'])                
                    adfMap._setNSDPThemeVisible(themeEntry, isNewlyVisible);
            }
        }        
    }    
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer.prototype._zoomListener = function(beforeZoomLevel, afterZoomLevel) 
{
    var mapId = this._mvMapViewId;    
    var adfMap = AdfPage.PAGE.findComponent(mapId);           
    
    adfMap.setProperty('currentZoom', afterZoomLevel.toString());    
    var needToLoadTheme = false;
    
    for (var i=0; i < adfMap._themeInfoTable.length; i++)
    {
        var themeEntry = adfMap._themeInfoTable[i];
        if (!themeEntry['loaded'])
        {
            var isAlreadyVisible = adfMap._isThemeVisibleinZoomLevel (themeEntry, beforeZoomLevel);
            var isNewlyVisible = adfMap._isThemeVisibleinZoomLevel (themeEntry, afterZoomLevel);
            if (isAlreadyVisible != isNewlyVisible)        
            {
                needToLoadTheme = true;
                break;
            }
        }
    }    
    
    if (needToLoadTheme)
        adfMap.getMVMapView().setLoadingIconVisible(true);

    var mapScaleChangeEvent = new AdfMapScaleChangeEvent(adfMap, beforeZoomLevel.toString(), afterZoomLevel.toString());
    mapScaleChangeEvent.setPartial(true);
    adfMap.queueEvent(mapScaleChangeEvent);    
}


AdfDhtmlGeoMapPeer.prototype._simulateMouseOnFOI = function (foi, state)  
{
    if (foi && foi['id'] != null)
    {
        var foiElem = document.getElementById(foi['id']);
        if (foiElem != null && 
            foiElem.firstChild != null &&
            foiElem.firstChild.firstChild != null)
        {
            if (state == 'mouseout' && foiElem.firstChild.firstChild.onmouseout != null)
                foiElem.firstChild.firstChild.onmouseout();
            else if (state == 'mouseover' && foiElem.firstChild.firstChild.onmouseover != null)
                foiElem.firstChild.firstChild.onmouseover();
        }
    }
}

AdfDhtmlGeoMapPeer.prototype.HandleComponentKeyDown = function (componentEvent) 
{
    var domEvent = componentEvent.getNativeEvent();
    var keyCode = domEvent.keyCode;
        
    var map = this.getComponent();
    var mapId = map.getClientId();

    var subIds = new Array();
    subIds[0] = AdfRichUIPeer.CreateSubId(mapId, "mapSwitch");
    subIds[1] = AdfRichUIPeer.CreateSubId(mapId, "satelliteMapSwitch");
    subIds[2] = AdfRichUIPeer.CreateSubId(mapId, "hybridMapSwitch");

    var focusThemeId = map._focusThemeId;
    if (focusThemeId == null) 
    {
        if (map._themeInfoTable != null && map._themeInfoTable.length > 0)
        {
            focusThemeId = map._themeInfoTable[0]['id'];
            map._focusThemeId = focusThemeId;
            map._focusFOIIndex = 0;
        }
    }


    var foiArray = null;
    var curThemeIndex = -1;
    if (focusThemeId != null)
    {
        foiArray = map._getFOIArray(focusThemeId);
        curThemeIndex = AdfDhtmlGeoMapPeer._getThemeInfoIndex(map._themeInfoTable, focusThemeId);            
    }
    
    var focusFOIIndex = map._focusFOIIndex;
    if (!focusFOIIndex)
        focusFOIIndex = 0;
            
    var isSelect = AdfAgent.AGENT.isSelectionToggle(domEvent);
        
    if (keyCode == AdfKeyStroke.ARROWLEFT_KEY && isSelect && foiArray != null) 
    {
        this._simulateMouseOnFOI(foiArray[focusFOIIndex], 'mouseout');
    
        // Key = J
        focusFOIIndex--;
        if (focusFOIIndex < 0)
        {
            focusFOIIndex = foiArray.length - 1;
        }                

        this._simulateMouseOnFOI(foiArray[focusFOIIndex], 'mouseover');        
    } else if (keyCode == AdfKeyStroke.ARROWRIGHT_KEY && isSelect && foiArray != null) 
    {
        this._simulateMouseOnFOI(foiArray[focusFOIIndex], 'mouseout');    
    
        // Key = K
        focusFOIIndex++;
        if (focusFOIIndex >= foiArray.length) 
        {
            focusFOIIndex = 0;
        }        
        
        this._simulateMouseOnFOI(foiArray[focusFOIIndex], 'mouseover');
    } else if (keyCode == 221)
    {
        // Key = ]
        var prevThemeIndex = curThemeIndex - 1;
        if (prevThemeIndex < 0)
            prevThemeIndex = map._themeInfoTable.length - 1;
                
        if (prevThemeIndex >= 0 && map._themeInfoTable[prevThemeIndex])
        {
            var prevThemeId = map._themeInfoTable[prevThemeIndex]['id'];
            focusThemeId = prevThemeId;
            focusFOIIndex = 0;        
        }
    } else if (keyCode == 219)
    {
        // Key = [
        var nextThemeIndex = curThemeIndex + 1;
        if (nextThemeIndex >= map._themeInfoTable.length)
            nextThemeIndex = 0;
        
        if (nextThemeIndex >= 0 && map._themeInfoTable[nextThemeIndex])
        {
            var nextThemeId = map._themeInfoTable[nextThemeIndex]['id'];            
            focusThemeId = nextThemeId;
            focusFOIIndex = 0;    
        }
    } else if (keyCode == AdfKeyStroke.ENTER_KEY) 
    {
        if (map._focusMapIndex != null)
        {
            mapElem = document.getElementById(subIds[map._focusMapIndex]);
            if (mapElem != null)
                mapElem.onmousedown();
            componentEvent.stopBubbling();
            componentEvent.cancel();            
            domEvent.stopPropagation();            
        } else if (foiArray != null && focusThemeId != null)
        {
            var foi = foiArray[focusFOIIndex];
            var point = MVSdoGeometry.createPoint(foi.x, foi.y, map.getMVMapView().srid);        
            this._clickFOI(foi, point, 'click', focusThemeId, foi.x, foi.y, null, 'left');            
        }
    } else if (keyCode == AdfKeyStroke.SPACE_KEY && isSelect && foiArray != null && focusThemeId != null) 
    {
        var foi = foiArray[focusFOIIndex];
        var point = MVSdoGeometry.createPoint(foi.x, foi.y, map.getMVMapView().srid);        
        this._clickFOI(foi, point, 'selection', focusThemeId, foi.x, foi.y, null, 'left');                        
    } else if (keyCode == AdfKeyStroke.TAB_KEY) {
        var mapElem = null;        
        var index = 0;
        if (map._focusMapIndex == null)
        {             
            mapElem = document.getElementById(subIds[0]);
        } else {
            index = map._focusMapIndex;
            var originalElement = document.getElementById(subIds[index]);
            if (originalElement != null)
                originalElement.onblur();
    
            if (!domEvent.shiftKey)            
            {
                index++;
                for (var j=index; j < 3 && mapElem == null; j++)            
                {
                    mapElem = document.getElementById(subIds[j]);
                    index = j;
                }
            } else {
                index--;
                for (var j=index; j >= 0 && mapElem == null; j--)            
                {
                    mapElem = document.getElementById(subIds[j]);
                    index = j;
                }                
            }
        }        
        
        if (mapElem != null)
        {
            map._focusMapIndex = index;
            mapElem.onfocus();                
            componentEvent.stopBubbling();
            componentEvent.cancel();
        } else {
            map._focusMapIndex = null;
        }
    } else if (keyCode == AdfKeyStroke.ESC_KEY) {
        map.getMVMapView().removeInfoWindow();
    } else if (keyCode == 79) {
        // Key = Ctrl-O
        if (map._overviewMap != null) 
        {
            if (!map._overviewMap.isCollapsed())    
                map._overviewMap.collapse();
            else
                map._overviewMap.minimizedIcon.parentNode.click();
        }
    } else {
    }

    map._focusThemeId = focusThemeId;
    map._focusFOIIndex = focusFOIIndex;    
}

AdfDhtmlGeoMapPeer.InitSubclass = function()
{
    AdfObject.ensureClassInitialization(AdfDhtmlGeoMapPeer); 
    AdfRichUIPeer.addSuppressedPPRAttributes(this, 'centerX');
    AdfRichUIPeer.addSuppressedPPRAttributes(this, 'centerY');    
    AdfRichUIPeer.addSuppressedPPRAttributes(this, 'currentZoom');    
    AdfRichUIPeer.addComponentEventHandlers(this, AdfUIInputEvent.KEY_DOWN_EVENT_TYPE);
}

AdfDhtmlGeoMapPeer.prototype.needsResizeNotify = function (component) 
{
    return true;
}

AdfDhtmlGeoMapPeer.prototype._createMapViewCallback = function (responseXML, responseText) 
{   
    var mapId = this.getClientId();
    var mapStyleElem = document.getElementById(AdfRichUIPeer.CreateSubId(mapId, "mapStyle"));            
        
    if (responseText != null && responseText.length > 0)
    {
        AdfPage.PAGE.__perfTimings(false,false,false, "MapViewer Connection OK");
        var dataElement = document.getElementById(AdfRichUIPeer.CreateSubId(mapId, "Data"));

        var peer = this.getPeer();
        AdfPage.PAGE.__perfTimings(false,false,false, "Before GeoMap Render: " + mapId);
        peer._initMapView(dataElement, mapStyleElem);
        
        var mapTool = this._mapTool;
        this._mapTool = "";
        this.setMapTool(mapTool);                    
    } else
    {
       var mapServerURL = mapStyleElem.getAttribute('mapServerURL');        
       var valueArray = new Array();
       valueArray.push(mapServerURL);
       var message = AdfDhtmlGeoMapPeer._messageFormat(AdfDhtmlGeoMapPeer._ERROR_MSG_26017, valueArray);
       AdfDhtmlGeoMapPeer._showErrorMessage(message);
       AdfPage.PAGE.__perfTimings(false,false,false, "MapViewer Connection Failed");
    }
}

AdfDhtmlGeoMapPeer.prototype._checkConnectionAndRunMapViewer = function ()
{    
    var elemId = this._component.getClientId();
    var mapStyleElem = document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "mapStyle"));            
    
    var serverContextPath = mapStyleElem.getAttribute('contextPath');
    var proxyPath = mapStyleElem.getAttribute('proxyPath');
    var mapServerURL = mapStyleElem.getAttribute('mapServerURL');    
    
    if (mapServerURL != null)
    {    
        var param = "rtarget=" + mapServerURL + "/omserver" + "&getv=t";
        var createCallback = this._component.createCallback(this._createMapViewCallback);               
        var connection = new MapAJAXConnection(proxyPath, createCallback);
        AdfPage.PAGE.__perfTimings(false,false,false, "Sending MapViewer Ajax request ...");
        connection.doPost(param);
    }
}

AdfDhtmlGeoMapPeer.prototype.ResizeNotify = function(oldWidth, oldHeight, newWidth, newHeight) 
{    
    var elemId = this._component.getClientId();
    
    if (newWidth != null && newHeight != null)
    {
        var mapElem = document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "actualMap"));
        if (mapElem != null)
        {
            mapElem.style.width = newWidth.toString() + "px";
            mapElem.style.height = newHeight.toString() + "px";
            if (this._component._mapview != null)
            {
                AdfDhtmlGeoMapPeer._adjustInfoWindowWidth(elemId);
            }
        }
    }    
    
    if (this._component._mapview == null)
    {
        var isPending = AdfPage.PAGE.isStreamingRequestPending(elemId);
        this._component._isPending = isPending;

        if (!this._isAda) {
            this._checkConnectionAndRunMapViewer();
        }
    }
 }

AdfDhtmlGeoMapPeer.prototype.DomReplaceNotify = function(domNode)
{
    var elemId = this._component.getClientId();
    
    if (domNode['id'] == AdfRichUIPeer.CreateSubId(elemId, "Data"))
    {
        var dataElement = document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "Data"));
        var mapStyleElem = document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "mapStyle"));            
        this._component.setProperty('centerX', mapStyleElem.getAttribute('centerX'));
        this._component.setProperty('centerY', mapStyleElem.getAttribute('centerY'));
        this._component.setProperty('currentZoom', mapStyleElem.getAttribute('currentZoom'));
        this._component.setProperty('centerSrid', mapStyleElem.getAttribute('srid'));            

        if (this._component._overviewContainerId != null)
        {
            var ovElem = document.getElementById(this._component._overviewContainerId);
            var heightInPx = 0;
            if (ovElem != null)
                heightInPx = parseInt(ovElem.style.height);
            
            if (heightInPx <= 20)
                mapStyleElem.setAttribute('overviewMapHideInit', 'true');
            else
                mapStyleElem.removeAttribute('overviewMapHideInit');
        }
        
        if (this._component._navigatorDecoration != null)
        {
            this._component.getMVMapView().removeMapDecoration(this._navigatorDecoration);
            this._component._navigatorDecoration = null;
        }

        var isPending = AdfPage.PAGE.isStreamingRequestPending(elemId);
        this._component._isPending = isPending;
        this._component._isPPR = true;
        AdfPage.PAGE.__perfTimings(false,false,false, "Before GeoMap Render: " + elemId);
        this._initMapView(dataElement, mapStyleElem);
        
        // reset the map tool
        var mapTool = this._component._mapTool;
        this._component._mapTool = "";
        this._component.setMapTool(mapTool);

        this._component._refreshZoombar();
    } else if (domNode['id'] == AdfRichUIPeer.CreateSubId(elemId, "hiddenLegend")) 
    {
        domNode.style.display = 'none';
    }
    
    return domNode;
}

AdfDhtmlGeoMapPeer.prototype._initResource = function ()
{
    var resourceId = AdfRichUIPeer.CreateSubId(this._component.getClientId(), "resource");
    var resourceElem = document.getElementById(resourceId);
    if (resourceElem != null)
    {
        AdfDhtmlGeoMapPeer._LATITUDE = resourceElem.getAttribute('LATITUDE'); 
        AdfDhtmlGeoMapPeer._LONGITUDE = resourceElem.getAttribute('LONGITUDE'); 
        AdfDhtmlGeoMapPeer._X = resourceElem.getAttribute('X'); 
        AdfDhtmlGeoMapPeer._Y = resourceElem.getAttribute('Y'); 
        AdfDhtmlGeoMapPeer._DISTANCE = resourceElem.getAttribute('DISTANCE'); 
        AdfDhtmlGeoMapPeer._AREA = resourceElem.getAttribute('AREA'); 
        AdfDhtmlGeoMapPeer._RADIUS = resourceElem.getAttribute('RADIUS'); 
        AdfDhtmlGeoMapPeer._MILES = resourceElem.getAttribute('MILES'); 
        AdfDhtmlGeoMapPeer._METERS = resourceElem.getAttribute('METERS'); 
        AdfDhtmlGeoMapPeer._KILOMETERS = resourceElem.getAttribute('KILOMETERS'); 
        AdfDhtmlGeoMapPeer._FEET = resourceElem.getAttribute('FEET'); 
        AdfDhtmlGeoMapPeer._SQUARE_KILOMETERS = resourceElem.getAttribute('SQUARE_KILOMETERS'); 
        AdfDhtmlGeoMapPeer._SQUARE_FEET = resourceElem.getAttribute('SQUARE_FEET');  
        AdfDhtmlGeoMapPeer._ACRES = resourceElem.getAttribute('ACRES'); 
        AdfDhtmlGeoMapPeer._SQUARE_MILES = resourceElem.getAttribute('SQUARE_MILES'); 
        AdfDhtmlGeoMapPeer._SQUARE_METERS = resourceElem.getAttribute('SQUARE_METERS'); 
        AdfDhtmlGeoMapPeer._MAP_VIEW = resourceElem.getAttribute('MAP_VIEW'); 
        AdfDhtmlGeoMapPeer._SATELLITE_VIEW = resourceElem.getAttribute('SATELLITE_VIEW'); 
        AdfDhtmlGeoMapPeer._MIXED_VIEW = resourceElem.getAttribute('MIXED_VIEW'); 
        MVMessages.panNWInfoTip = resourceElem.getAttribute('MVMessages_panNWInfoTip'); 
        MVMessages.panNInfoTip = resourceElem.getAttribute('MVMessages_panNInfoTip'); 
        MVMessages.panNEInfoTip = resourceElem.getAttribute('MVMessages_panNEInfoTip'); 
        MVMessages.panSWInfoTip = resourceElem.getAttribute('MVMessages_panSWInfoTip'); 
        MVMessages.panSInfoTip = resourceElem.getAttribute('MVMessages_panSInfoTip'); 
        MVMessages.panSEInfoTip = resourceElem.getAttribute('MVMessages_panSEInfoTip'); 
        MVMessages.panWInfoTip = resourceElem.getAttribute('MVMessages_panWInfoTip'); 
        MVMessages.panCenterInfoTip = resourceElem.getAttribute('MVMessages_panCenterInfoTip'); 
        MVMessages.panEInfoTip = resourceElem.getAttribute('MVMessages_panEInfoTip'); 
        MVMessages.sliderBarInfoTip = resourceElem.getAttribute('MVMessages_sliderBarInfoTip'); 
        MVMessages.sliderInfoTip = resourceElem.getAttribute('MVMessages_sliderInfoTip'); 
        MVMessages.zoomInInfoTip = resourceElem.getAttribute('MVMessages_zoomInInfoTip'); 
        MVMessages.zoomOutInfoTip = resourceElem.getAttribute('MVMessages_zoomOutInfoTip'); 
        AdfDhtmlGeoMapPeer.GROUP_SIZE = resourceElem.getAttribute('GROUP_SIZE'); 
        AdfDhtmlGeoMapPeer.GROUP_SEPARATOR = resourceElem.getAttribute('GROUP_SEPARATOR'); 
        AdfDhtmlGeoMapPeer.DECIMAL_SEPARATOR = resourceElem.getAttribute('DECIMAL_SEPARATOR'); 
        AdfDhtmlGeoMapPeer._ERROR_MSG_26017 = resourceElem.getAttribute('ERROR_MSG_26017'); 
        AdfDhtmlGeoMapPeer._ERROR_MSG_26018 = resourceElem.getAttribute('ERROR_MSG_26018'); 
    }
}

AdfDhtmlGeoMapPeer.prototype.InitDomElement = function(component, domElement)
{  
    AdfDhtmlGeoMapPeer.superclass.InitDomElement.call(this, component, domElement);
    
    this._component = component;
    this._domElement = domElement;
    
    this._component._mapTool = 'hand';
    this._component._overviewContainerId = null;    
    this._component._isPPR = false;
    this._initResource();
    
    var agent = AdfAgent.AGENT;
    var ada  = agent.getAttribute(domElement, "_ada");
    this._isAda = (ada!=undefined);
}

AdfDhtmlGeoMapPeer.prototype._getInitSrid = function () {
    var domElement = this._domElement;
    var elemId = domElement.getAttribute("id");
    var mapStyleElem = document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "mapStyle"));
    return parseInt(mapStyleElem.getAttribute('startSRID'));    
}

AdfDhtmlGeoMapPeer._splitCSS = function (css) {
    var styles = css.split(';');
    var obj = new Object();

    for (var i=0; i < styles.length; i++)
    {
        var nameValue = styles[i].split(':');
        if (nameValue != null && nameValue.length >= 2)
        {
            var name = nameValue[0].replace('-', '');
            obj[name] = nameValue[1];          
        }        
    }

    return obj;
}

AdfDhtmlGeoMapPeer.prototype._reloadNavigator = function () 
{
    var oldNavigator = this._component._navigatorDecoration;
    if (oldNavigator != null)
    {
        oldNavigator.getContainerDiv().onmousemove = null;
        this._initResource();        
        this._component._mapview.removeMapDecoration(oldNavigator);    
        this._component._navigatorDecoration = null;        
    }    

    this._component._refreshZoombar();    
}

/**
 * @export
 */
AdfDhtmlGeoMapPeer.prototype._initMapView = function (domElement, mapStyleElem)
{
  MVMapView.enableXMLHTTP(true);  
  
  var elemId = this._component.getClientId();     
  this._component._selectFOI = new Array();
  this._component._selectTheme = null;
  this._component._activeTheme = null;  
  this._component._rectangleTool = null;  
  this._component._circleTool = null;    
  this._component._redlineTool = null;    
  this._component._measureTool = null;    
  this._component._areaTool = null;    
  this._component._themeBasedFOIs = new Array();
  this._component._baseMap = null;
  this._component._satelliteMap = null;
  this._component._hybridMap = null;
  this._component._themeInfoTable = new Array();
  this._component._foiTheme = new Array();    
  
  var geocodeURL = "";
  
  if (domElement != null && mapStyleElem != null)
  {
          var mapServerURL = mapStyleElem.getAttribute('mapServerURL');
          var serverContextPath = mapStyleElem.getAttribute('contextPath');
          var proxyPath = mapStyleElem.getAttribute('proxyPath');
          var protocolIndex = proxyPath.indexOf('://');
          if (protocolIndex >= 0)
          {  
            // proxyPath should be relative to application domain
            // if the proxyPath starts with protocol and application domain
            // we want to strip that off
            proxyPath = proxyPath.substring(protocolIndex + 3);
            var pathRootIndex = proxyPath.indexOf('/');
            if (pathRootIndex >= 0)
                proxyPath = proxyPath.substring(pathRootIndex);
            else
                proxyPath = '/';  
          }          

          // Bug 13416899 : increasing memory consumption when using dvt:map component in adf application
          // 
          // study comments in ComponentRemoved
          // 
          if ( this._component._mapview ) {
            this._component._mapview.removeAllFOIs();
            this._component._mapview.destroy();
            this._component._mapview = null;
          }

          MVMapView.setProxyPath(proxyPath);        
          MVMapView.enableCodingHints(false);
          
          var baseURL = mapServerURL;
            
          this._component._mapview = new MVMapView(document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "actualMap")), baseURL);          
          var closeImagePath = mapStyleElem.getAttribute('CLOSE_IMAGE_PATH');
          var winHeaderPath = mapStyleElem.getAttribute('WINHEADER_IMAGE_PATH');
        
          var infoConeStyle = mapStyleElem.getAttribute('infoWindowConeStyle');
          var infoBodyStyle = mapStyleElem.getAttribute('infoWindowBodyStyle');
          var infoTBStyle = "background-image:url('" + winHeaderPath + "');" + mapStyleElem.getAttribute('infoWindowTitleBarStyle');

          var parameters = {'closeButtonImageURL': closeImagePath,
                            'titleBarStyle': infoTBStyle,
                            'bodyStyle': infoBodyStyle,
                            'coneStyle': infoConeStyle};
          this._component._mapview.setDefaultInfoWindowStyle('MVInfoWindowStyle1', parameters);
          this._component._mapview.removeAllFOIs();
          this._component._mapview._mvMapViewId = elemId;
              
          geocodeURL = mapStyleElem.getAttribute('mapGeocodeServerURL');          
          var baseMapName = mapStyleElem.getAttribute('baseMapName');        
          var satelliteMap = mapStyleElem.getAttribute('satelliteMap');
          var hybridMap = mapStyleElem.getAttribute('hybridMap');
          var me = this;
          
          var customCallback = function () {          
              // attribute changes
              var longitude = parseFloat(me._component.getProperty('centerX'));
              var latitude = parseFloat(me._component.getProperty('centerY'));
              var zoomLevel = parseInt(me._component.getProperty('currentZoom'));
              var srid = parseInt(me._component.getProperty('centerSrid'));
    
              var originalX = parseFloat(mapStyleElem.getAttribute('startX'));
              var originalY = parseFloat(mapStyleElem.getAttribute('startY'));
              var originalScale = parseInt(mapStyleElem.getAttribute('startZoom'));
              var originalSrid = parseInt(mapStyleElem.getAttribute('startSRID'));              
              var originalPoint = MVSdoGeometry.createPoint(originalX, originalY, originalSrid);
                  
              if (mapStyleElem.getAttribute('autoZoomTheme') == null || !me._component._isPPR) 
              {                  
                  me._component._mapview.setCenter(originalPoint);
                  me._component._mapview.setZoomLevel(originalScale);                 
              } else {
                  var centerPoint = MVSdoGeometry.createPoint(longitude, latitude, srid);
                  me._component._mapview.setCenter(centerPoint);                  
                  me._component._mapview.setZoomLevel(zoomLevel);
              }
              
              me._component._mapview.setMouseWheelZoomEnabled(true);                                    
              me._component._mapview.setHomeMap(originalPoint, originalScale);        
              
              
              // event Listener
              me._component._mapview.addEventListener("mouse_click", me._MapClick);
              me._component._mapview.addEventListener("mouse_double_click", me._doubleClick);
              me._component._mapview.addEventListener("mouse_right_click", me._MapRTCancel);
              me._component._mapview.addEventListener("before_zoom_level_change", me._beforeZoomListener);                        
              me._component._mapview.addEventListener("zoom_level_change", me._zoomListener);          
              me._component._mapview.addEventListener("recenter", me._recenterListener);
        
              me._component._unit = mapStyleElem.getAttribute('unit');              
              
              me._component._mapview.display();  

              var resourceLoading = function (evt) {
                  me._reloadNavigator();
              }
            
              // attribute changes
              if (mapStyleElem.getAttribute('navigatorPosition') != null)
              {
                  me._component._refreshZoombar();
                  if (me._component._navigatorDecoration.getContainerDiv())
                    me._component._navigatorDecoration.getContainerDiv().onmousemove = resourceLoading;                  
              } 
              
              if (mapStyleElem.getAttribute('hasTheme') != null)
              {
                  if (AdfPage.PAGE.isStreamingDisabled() || !me._component._isPending)
                  {
                      me._component._mapview.setLoadingIconVisible(true);            
                      me._loadTheme(me._component, true);              
                  } 
                  
                  me._component._isPending = null;
              }
              
              if (mapStyleElem.getAttribute('overviewMapHidden') == null)               
              {
                  var overviewMapWidth = 200;
                  if (mapStyleElem.getAttribute('overviewMapWidth') != null)
                      overviewMapWidth = parseInt(mapStyleElem.getAttribute('overviewMapWidth'));

                  var overviewMapHeight = 150;
                  if (mapStyleElem.getAttribute('overviewMapHeight') != null)
                      overviewMapHeight = parseInt(mapStyleElem.getAttribute('overviewMapHeight'));

                  var overviewMapDiff = 3;
                  if (mapStyleElem.getAttribute('overviewMapDiff') != null)
                      overviewMapDiff = parseInt(mapStyleElem.getAttribute('overviewMapDiff'));
                                   
                  var overviewMapInitHidden = (mapStyleElem.getAttribute('overviewMapHideInit') != null);
                  ovcontainer = new MVMapDecoration(null, null, null, overviewMapWidth, overviewMapHeight);

                  var contextPath = me._component._getContextPath();
                  var handCursorPath = me._component._getStyleElement().getAttribute('HANDCUR');

                  if (AdfAgent.getAgent().getPlatform() == AdfAgent.IE_PLATFORM) 
                  {
                     ovcontainer.setMouseCursorStyle(handCursorPath);        
                  } else
                  {                   
                     cursorStyles = new Array();
                     cursorStyles.push("url('" + handCursorPath + "')");
                     cursorStyles.push("default");
                     ovcontainer.setMouseCursorStyle(cursorStyles);                
                  }             

                  var ovEnaPath = mapStyleElem.getAttribute('overview-window-header-icon');
                  var ovDwnPath = mapStyleElem.getAttribute('overview-window-header-active-icon');
                  var ovOvrPath = mapStyleElem.getAttribute('overview-window-header-hover-icon');

                  var panCloseEnaPath= mapStyleElem.getAttribute('overview-window-maximize-icon');
                  var panCloseDwnPath= mapStyleElem.getAttribute('overview-window-maximize-active-icon');
                  var panCloseOvrPath= mapStyleElem.getAttribute('overview-window-maximize-hover-icon');

                  var panOpenEnaPath= mapStyleElem.getAttribute('overview-window-minimize-icon');
                  var panOpenDwnPath= mapStyleElem.getAttribute('overview-window-minimize-active-icon');
                  var panOpenOvrPath= mapStyleElem.getAttribute('overview-window-minimize-hover-icon');
   
                  var ovStyle = 
                  { 
                    'titleBgImg': ovEnaPath,
                    'titleBgImgMO': ovOvrPath,
                    'titleBgImgMD': ovDwnPath,
                    'minBtnImg':   panCloseEnaPath, 
                    'minBtnImgMO': panCloseOvrPath,
                    'minBtnImgMD': panCloseDwnPath,
                    'resBtnImg':   panOpenEnaPath, 
                    'resBtnImgMO': panOpenOvrPath, 
                    'resBtnImgMD': panOpenDwnPath} ;

                  ovcontainer.setCollapsible(true, overviewMapInitHidden, ovStyle);

                  me._component._mapview.addMapDecoration(ovcontainer);
                  me._component._overviewMap = ovcontainer;
                  var over=new MVOverviewMap(ovcontainer.getContainerDiv(),overviewMapDiff);
                  var overviewAreaStyle = mapStyleElem.getAttribute('overviewMapAreaStyle');
                  var ovCSSObj = AdfDhtmlGeoMapPeer._splitCSS(overviewAreaStyle);
                  over.setRectangleStyle(ovCSSObj.border, ovCSSObj['backgroundcolor']);                  

                  me._component._overviewContainerId = ovcontainer.getContainerDiv()['id'];
                  ovcontainer.getContainerDiv().className = mapStyleElem.getAttribute('overviewMapBodyClass');
                      
                  me._component._mapview.addOverviewMap(over);                                        
              }
                            
              var mapDomElement = document.getElementById(AdfRichUIPeer.CreateSubId(elemId, "actualMap"));
              mapWidth = parseInt(mapDomElement.style.width);                         

              if (mapStyleElem.getAttribute('isShowScaleBar') != null)
              {
                  var isGeodetic = (me._component._mapview.srid != 8307);
                  var mvScaleBar = null;
                  if (isGeodetic)
                      mvScaleBar = new MVScaleBar(true);
                  else
                      mvScaleBar = new MVScaleBar();

                  var scaleBarBar = mapStyleElem.getAttribute('scaleBarBarStyle');
                  var scaleBarText = mapStyleElem.getAttribute('scaleBarTextStyle');

                  var scaleBarStyle = { 
                    'barStyle':scaleBarBar,
                    'barHeight':1,
                    'textStyle':scaleBarText
                  } ;
                  
                  mvScaleBar.setStyle(scaleBarStyle);
                  var scaleBar = new MVMapDecoration(mvScaleBar, 0.0, 1.0);
                  //BUG 34184877 - MAKE DVT COMPATIBLE WITH CSP STANDARDS
                  var proxyFunc=function anonymous() 
                  {
                    this.getContainerDiv().title="";
                  }
                  scaleBar.setEventListener('mouse_over', proxyFunc);
                  scaleBar.enableEventPropagation(true);                  
                  scaleBar.setOffset(5, -54);        
                  me._component._mapview.addMapDecoration(scaleBar);
              }
              
              var copyrightClass = mapStyleElem.getAttribute('copyrightStyleClass');      
              var copyrightText = mapStyleElem.getAttribute('copyrightText');                    
              var copyRightElem = new MVMapDecoration("<table width='0' border='0' cellspacing='0' cellpadding='0'><tr><td nowrap class='" + copyrightClass + "'><div id='" + elemId + AdfDhtmlGeoMapPeer.NAMING_SEPARATOR + "copyrightText'>" + copyrightText + "</div></td></tr></table>", 0.0, 1.0, 0, 0);
              copyRightElem.enableEventPropagation(true);              
              copyRightElem.setOffset(5, -12);              
              me._component._mapview.addMapDecoration(copyRightElem);
                            
              if (me._component._themeIsInit == null && me._component._initThemeFunction != null) 
              {
                  me._component._initThemeFunction();
              }
              
              me._component._callbackIsCalled = true;
              AdfPage.PAGE.__perfTimings(true,false,false, "After GeoMap Render: " + elemId);
          }

          var mapControlClass = mapStyleElem.getAttribute('mapControlStyleClass');      
          var mapControlNotSelectClass = mapStyleElem.getAttribute('mapControlStyleClassNotSelect');                
          var mapControlOverClass = mapStyleElem.getAttribute('mapControlStyleClassOver');
          
          this._component._baseMap = new MVBaseMap(baseMapName);          
          this._component._baseMap.setVisible(true);
          this._component._mapview.addMapTileLayer(this._component._baseMap, customCallback);            

          if (satelliteMap != null)
          {
              this._component._satelliteMap = new MVBaseMap(satelliteMap);
              this._component._satelliteMap.setVisible(false);                                                      
              this._component._mapview.addMapTileLayer(this._component._satelliteMap);                              
          }

          if (hybridMap != null)
          {
              this._component._hybridMap = new MVBaseMap(hybridMap);
              this._component._hybridMap.setTransparent (true);                  
              this._component._mapview.addMapTileLayer(this._component._hybridMap);                              
          }              
          
          this._addMapControl (this._component, mapControlClass, mapControlNotSelectClass, mapControlOverClass);
      } 
}

AdfDhtmlGeoMapPeer.prototype._getMapControlDiv = function (id, defaultClass, selectClass, notSelectClass, mouseoverClass, label) 
{
    return "<div id='" + id + "' class='" + defaultClass + 
           "' onmousedown='AdfDhtmlGeoMap._selectMapType(this)' " +
           "onmouseover=\"if(this.className!='" + selectClass + "') this.className='" + mouseoverClass + "'\"  " +
           "onmouseout=\"if(this.className!='" + selectClass + "')this.className='" + notSelectClass + "'\" " +
           "onfocus=\"if(this.className!='" + selectClass + "') this.className='" + mouseoverClass + "'\"  " +
           "onblur=\"if(this.className!='" + selectClass + "')this.className='" + notSelectClass + "'\">" +           
           label +
           "</div>";
}

AdfDhtmlGeoMapPeer.prototype._addMapControl = function (adfMap, styleClass, notSelectStyleClass, overClass) 
{    
    var mapTypeControl = "<table><tr><td nowrap>" + this._getMapControlDiv(AdfRichUIPeer.CreateSubId(adfMap.getClientId(), 'mapSwitch'), styleClass, styleClass, notSelectStyleClass, overClass, AdfDhtmlGeoMapPeer._MAP_VIEW) + "</td>";
      
    if (adfMap._satelliteMap != null || adfMap._hybridMap != null)
    {
        if (adfMap._satelliteMap != null)
            mapTypeControl += "<td nowrap>" + this._getMapControlDiv(AdfRichUIPeer.CreateSubId(adfMap.getClientId(), 'satelliteMapSwitch'), notSelectStyleClass, styleClass, notSelectStyleClass, overClass,  AdfDhtmlGeoMapPeer._SATELLITE_VIEW) + "</td>";        
            
        if (adfMap._hybridMap != null)
            mapTypeControl += "<td nowrap>" + this._getMapControlDiv(AdfRichUIPeer.CreateSubId(adfMap.getClientId(), 'hybridMapSwitch'), notSelectStyleClass, styleClass, notSelectStyleClass, overClass,  AdfDhtmlGeoMapPeer._MIXED_VIEW) + "</td>";                

        mapTypeControl += "</td></tr></table>";
        
        var md = new MVMapDecoration(mapTypeControl, 1.0, 0, 100, 20);
        md.setOffset(-200, 5);
        adfMap.getMVMapView().addMapDecoration(md);                
    }     
}

AdfDhtmlGeoMapPeer.prototype._loadTheme = function (component, forceReload)
{ 
    var event = new AdfMapThemeLoadEvent(component, forceReload);
    event.setPartial(true);
    component.queueEvent(event);
}


AdfDhtmlGeoMapPeer.prototype._getGeocodeRequest = function (geocodeElem) 
{
   var geocodeType = geocodeElem.getAttribute ('geocodeType'); 
   var geoCodeRequest = "<?xml version=\"1.0\" standalone=\"yes\"?>" +
                        "<geocode_request vendor=\"elocation\">" +
                        "<address_list>" +
                        "<input_location id=\"1\">" +
                        "<input_address match_mode=\"relax_street_type\">";
                                
   if (geocodeType == '1')
   {
        geoCodeRequest += "<us_form1 ";
        
        if (geocodeElem.getAttribute('name'))
            geoCodeRequest += "name=\"" + geocodeElem.getAttribute('name') + "\" ";
        
        if (geocodeElem.getAttribute('intersecting'))
            geoCodeRequest += "intersecting_street=\"" + geocodeElem.getAttribute('intersecting') + "\" ";

        if (geocodeElem.getAttribute('street'))
            geoCodeRequest += "street=\"" + geocodeElem.getAttribute('street') + "\" ";

        if (geocodeElem.getAttribute('lastline'))                    
            geoCodeRequest += "lastline=\"" + geocodeElem.getAttribute('lastline') + "\" ";                                     
   } else if (geocodeType == '2') 
   {
        geoCodeRequest += "<us_form2 ";
        
        if (geocodeElem.getAttribute('name'))
            geoCodeRequest += "name=\"" + geocodeElem.getAttribute('name') + "\" ";
        
        if (geocodeElem.getAttribute('intersecting'))
            geoCodeRequest += "intersecting_street=\"" + geocodeElem.getAttribute('intersecting') + "\" ";

        if (geocodeElem.getAttribute('street'))
            geoCodeRequest += "street=\"" + geocodeElem.getAttribute('street') + "\" ";

        if (geocodeElem.getAttribute('city'))                    
            geoCodeRequest += "city=\"" + geocodeElem.getAttribute('city') + "\" ";                                     
            
        if (geocodeElem.getAttribute('state'))                    
            geoCodeRequest += "state=\"" + geocodeElem.getAttribute('state') + "\" ";                                     
            
        if (geocodeElem.getAttribute('zipcode'))                    
            geoCodeRequest += "zip_code=\"" + geocodeElem.getAttribute('zipcode') + "\" ";                                            
   } else if (geocodeType == '3') 
   {
        geoCodeRequest += "<gen_form ";
        
        if (geocodeElem.getAttribute('name'))
            geoCodeRequest += "name=\"" + geocodeElem.getAttribute('name') + "\" ";
        
        if (geocodeElem.getAttribute('intersecting'))
            geoCodeRequest += "intersecting_street=\"" + geocodeElem.getAttribute('intersecting') + "\" ";

        if (geocodeElem.getAttribute('street'))
            geoCodeRequest += "street=\"" + geocodeElem.getAttribute('street') + "\" ";

        if (geocodeElem.getAttribute('subArea'))                    
            geoCodeRequest += "sub_area=\"" + geocodeElem.getAttribute('subArea') + "\" ";                                     
            
        if (geocodeElem.getAttribute('city'))                    
            geoCodeRequest += "city=\"" + geocodeElem.getAttribute('city') + "\" ";                                     

        if (geocodeElem.getAttribute('region'))                    
            geoCodeRequest += "region=\"" + geocodeElem.getAttribute('region') + "\" ";                                     

        if (geocodeElem.getAttribute('country'))                    
            geoCodeRequest += "country=\"" + geocodeElem.getAttribute('country') + "\" ";                                            
            
        if (geocodeElem.getAttribute('postalCode'))                    
            geoCodeRequest += "postal_code=\"" + geocodeElem.getAttribute('postalCode') + "\" ";                                            
            
        if (geocodeElem.getAttribute('postalCodeAddOn'))                    
            geoCodeRequest += "postal_addon_code=\"" + geocodeElem.getAttribute('postalCodeAddOn') + "\" ";                                                        
   } else if (geocodeType == '4') 
   {
        geoCodeRequest += "<gdf_form ";
        
        if (geocodeElem.getAttribute('name'))
            geoCodeRequest += "name=\"" + geocodeElem.getAttribute('name') + "\" ";
        
        if (geocodeElem.getAttribute('intersecting'))
            geoCodeRequest += "intersecting_street=\"" + geocodeElem.getAttribute('intersecting') + "\" ";

        if (geocodeElem.getAttribute('street'))
            geoCodeRequest += "street=\"" + geocodeElem.getAttribute('street') + "\" ";

        if (geocodeElem.getAttribute('builtupArea'))                    
            geoCodeRequest += "builtup_area=\"" + geocodeElem.getAttribute('builtupArea') + "\" ";                                     

        if (geocodeElem.getAttribute('order8Area'))                    
            geoCodeRequest += "order8_area=\"" + geocodeElem.getAttribute('order8Area') + "\" ";                                     

        if (geocodeElem.getAttribute('order2Area'))                    
            geoCodeRequest += "order2_area=\"" + geocodeElem.getAttribute('order2Area') + "\" ";                                     

        if (geocodeElem.getAttribute('orderArea'))                    
            geoCodeRequest += "order1_area=\"" + geocodeElem.getAttribute('orderArea') + "\" ";                                     
            
        if (geocodeElem.getAttribute('country'))                    
            geoCodeRequest += "country=\"" + geocodeElem.getAttribute('country') + "\" ";                                            
            
        if (geocodeElem.getAttribute('postalCode'))                    
            geoCodeRequest += "postal_code=\"" + geocodeElem.getAttribute('postalCode') + "\" ";                                            
            
        if (geocodeElem.getAttribute('postalCodeAddOn'))                    
            geoCodeRequest += "postal_addon_code=\"" + geocodeElem.getAttribute('postalCodeAddOn') + "\" ";                                                               
   } else if (geocodeType == '5') 
   {
        geoCodeRequest += "<unformatted ";
        
        if (geocodeElem.getAttribute('name'))
            geoCodeRequest += "name=\"" + geocodeElem.getAttribute('name') + "\" ";
            
        if (geocodeElem.getAttribute('country'))                    
            geoCodeRequest += "country=\"" + geocodeElem.getAttribute('country') + "\" ";                                            

        if (geocodeElem.getAttribute('unformattedLine'))                    
            geoCodeRequest += "address_line=\"" + geocodeElem.getAttribute('unformattedLine') + "\" "; 
   }
   
   
   geoCodeRequest += "/></input_address>" +
                     "</input_location>" +
                     "</address_list>" +
                     "</geocode_request>";                               
   
   return geoCodeRequest;
}


/**
 * @param {String} payload - 
 * @param {int} changeCount - Monotonically increasing Change count for this change
 * @return {boolean} Returns <code>true</code> if the component should continue to receive
 * active data events.
 * @override
 */ 
AdfDhtmlGeoMapPeer.prototype.ProcessPushData = function(payload, changeCount)
{
  var changeMessage = eval(payload);
  var themeId = changeMessage['t_id'];
  AdfLogger.LOGGER.fine("ProcessPushData. Theme id = ", themeId);

  var adfMap = this._component;                     
  var activeTheme = adfMap.getTheme(themeId);
  if (activeTheme == null) {
    return false;
  }

  var animationEffect = changeMessage['a_eff'];
  if (null == animationEffect)
    animationEffect = this._getDefaultAnimationEffect();

  var animationTime = changeMessage['a_time'];
  if (null == animationTime) {
    animationTime = this._getDefaultAnimationTime();
  }
    
  var changeList = changeMessage['c_l'];
  for(var i=0 ;i<changeList.length; i++)
  {
    var singleMessage = changeList[i];
    switch(singleMessage['type'])
    {
      case 'update':
        this._processPointThemeUpdate(themeId, singleMessage, animationEffect, animationTime);
      break;
      case 'remove':
        this._processPointThemeRemove(themeId, singleMessage, animationEffect, animationTime);
      break;
      case 'insert':
        this._processPointThemeInsert(themeId, singleMessage, animationEffect, animationTime);
      break;
    }
  }
  return true;
}

AdfDhtmlGeoMapPeer.prototype._processPointThemeUpdate = function(
                                                  themeId, singleMessage, 
                                                  animationEffect, animationTime)
{
  AdfLogger.LOGGER.fine("_processPointThemeUpdate. Message =" + singleMessage);

  var pointId = singleMessage['p_id'];
  var pointFOI = this._component._mapview.getFOI(pointId);
  if (null == pointFOI) {
    return false;
  }
  
  var changeData = singleMessage['c_data'];
  if (null == changeData)
    return false;
  
  var newLabel = changeData['label'];
  var newLatitude = changeData['lat'];
  var newLongitude = changeData['long'];  
  var newDataValue = changeData['pt_data_value']; 
  var newFormattedDataValue = changeData['pt_fmted_data_value'];
  var newDataValueAttrName = changeData['pt_data_value_column_name'];
  var newDataValueAttrLabel = changeData['pt_data_value_column_label'];
  var newImage = changeData['pt_image'];
  var newSelImage = changeData['pt_sel_image'];
  var newHoverImage = changeData['pt_hover_image'];

  this._updatePointFOI(pointFOI, newLabel, newLongitude, newLatitude, 
                       newDataValue, newFormattedDataValue, 
                       newDataValueAttrName, newDataValueAttrLabel,
                       newImage, newSelImage, newHoverImage, 
                       animationEffect, animationTime);
  
  return true;
}

AdfDhtmlGeoMapPeer.prototype._getPointLongitude = function(pointFOI) 
{
    return pointFOI._originalPointX;
}

AdfDhtmlGeoMapPeer.prototype._getPointLatitude = function(pointFOI) 
{
  return pointFOI._originalPointY;
}

AdfDhtmlGeoMapPeer.prototype._processPointThemeRemove = function(
                                                        themeId, singleMessage, 
                                                        animationEffect, animationTime)
{
  AdfLogger.LOGGER.fine("_processThemeRemove. Message =" + singleMessage);
  var pointId = singleMessage['p_id'];
  
  return this._processPointFOIRemove(themeId, pointId, animationEffect, animationTime);
}

AdfDhtmlGeoMapPeer.prototype._processPointFOIRemove = function(
                                                themeId, pointId, 
                                                animationEffect, animationTime) {
  var pointFOI = this._component._mapview.getFOI(pointId);
  if (null == pointFOI) {
    return false;
  }

  var deleteCallback = "AdfDhtmlGeoMapPeer.removePointFOICallback('" + 
                       this._component.getClientId() + "', '" + themeId + "', '" 
                       + pointId + "')";
  this._animatePointFOIRemove(pointId, animationEffect, animationTime, deleteCallback);

  return true;  
}

AdfDhtmlGeoMapPeer.removePointFOICallback = function(mapId, themeId, pointId) {
  var mapComponent = null;
  if (mapId != null)
    mapComponent = AdfPage.PAGE.findComponent(mapId);                     

  if (null == mapComponent || 'undefined' == mapComponent) {
    return false;
  }
  
  var pointFOI = mapComponent._mapview.getFOI(pointId);
  if (null == pointFOI) {
    return false;
  }

  var themeFOIArray = mapComponent._foiTheme[themeId];
  var pointIndex = -1;
  for (var i = 0; i < themeFOIArray.length; i++) {
    var curPointFOI = themeFOIArray[i];
    if (curPointFOI['id'] == pointFOI['id']) {
      pointIndex = i;
      break;
    }
  }
  
  if (pointIndex == -1)
    return false;
  
  themeFOIArray.splice(pointIndex, 1);
  
  mapComponent._mapview.removeFOI(pointId);
}

AdfDhtmlGeoMapPeer.prototype._animatePointFOIRemove = function(
                                      pointId, animationEffect, 
                                      animationTime, pointRemoveCallback) {
  if ('a_eff_blink' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'blink', pointRemoveCallback);
  }
  else if ('a_eff_blink_n_fade' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'blink_and_fade_out', pointRemoveCallback);
  }
  else if ('a_eff_fade' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'fade_out', pointRemoveCallback);
  }
}

AdfDhtmlGeoMapPeer.prototype._getPointIndex = function(targetArray, pointFOI) {
  for (var i = 0; i < targetArray.length; i++) {
    var curPointFOI = targetArray[i];
    if (curPointFOI['id'] == pointFOI['id'])
      return i;
  }
  return -1;
}

AdfDhtmlGeoMapPeer.prototype._processPointThemeInsert = function(
                                                        themeId, singleMessage, 
                                                        animationEffect, animationTime)
{
  AdfLogger.LOGGER.fine("_processPointThemeInsert. Message =" + singleMessage);

  var pointId = singleMessage['p_id'];

  var changeData = singleMessage['c_data'];
  if (null == changeData)
    return false;
    
  var newLabel = changeData['label'];
  var newLatitude = changeData['lat'];
  var newLongitude = changeData['long'];  
  var dataValue = changeData['pt_data_value']; 
  var formattedDataValue = changeData['pt_fmted_data_value'];
  var dataValueAttrName = changeData['pt_data_value_column_name'];
  var dataValueAttrLabel = changeData['pt_data_value_column_label'];
  var image = changeData['pt_image'];
  var selImage = changeData['pt_sel_image'];
  var hoverImage = changeData['pt_hover_image'];
  var categoryValue = changeData['cat'];
  var locationLabelValue = changeData['location_label'];
  
  var newPointFOI = this._createPointFOI(
                    themeId, pointId, newLabel, newLongitude, newLatitude, 
                    dataValue, formattedDataValue, 
                    dataValueAttrName, dataValueAttrLabel,
                    image, selImage, hoverImage, categoryValue, newLabel);  
  
  if (!this._isThemeVisible(themeId)) {
    newPointFOI.setVisible(false);
    this._addAdsPointFOI(newPointFOI, themeId);
    return true;
  }
  
  this._component._updateImageWidthHeight(themeId, image, "AdfDhtmlGeoMapPeer._animatePointFOIInsert('" + pointId +"', '" + animationEffect +"', "+ animationTime.toString() + ");");

  return true;  
}

AdfDhtmlGeoMapPeer.prototype._isThemeVisible = function(themeId) {
  // figure out the visible property from the current theme points
  var themeFOIArray = this._component._foiTheme[themeId];
  return themeFOIArray[0].isVisible();
}

AdfDhtmlGeoMapPeer._animatePointFOIInsert = function(pointId, animationEffect) {
  if ('a_eff_blink' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'blink');
  }
  else if ('a_eff_blink_n_fade' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'fade_in_and_blink');
  }
  else if ('a_eff_fade' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'fade_in');
  }
}

AdfDhtmlGeoMapPeer.prototype._addAdsPointFOI = function(newPointFOI, themeId) {
  this._component._mapview.addFOI(newPointFOI);

  var themeFOIArray = this._component._foiTheme[themeId];
  themeFOIArray.push(newPointFOI);
}

AdfDhtmlGeoMapPeer.prototype._updatePointFOI = function(
                             pointFOI, pointLabel, longitude, latitude, 
                             dataValue, formattedDataValue, 
                             dataAttrName, dataAttrLabel,
                             pointImage, pointSelectedImage, pointHoverImage, 
                             animationEffect, animationTime) {
  if (null == pointFOI)
    return false;

  var pointChanged = false;
  var imageChanged = false;
  
  if (pointLabel != null && pointLabel != pointFOI['name']) {
    pointFOI['name'] = pointLabel;
    pointChanged = true;
  }
  
  if (dataAttrLabel != null && dataAttrLabel != pointFOI['attrnames'][0]) {
    pointFOI['attrnames'] = new Array(dataAttrLabel, '__adf_item_Label0');
    pointChanged = true;
  }    
  
  if (dataValue != null && formattedDataValue != null) {
    pointFOI['attrs'] = new Array(dataValue, formattedDataValue);
    pointChanged = true;
  }
  
  if (pointImage != null && pointImage != pointFOI.originalImages) {
    pointFOI.originalImages = pointImage;
    pointChanged = true;
    imageChanged = true;
  }    

  if (pointSelectedImage != null && pointSelectedImage != pointFOI.selectedImages) {
    pointFOI.selectedImages = pointSelectedImage;
    pointChanged = true;
  }

  if (pointHoverImage != null && pointHoverImage != pointFOI.hoverImage) {
    pointFOI._hoverHTML = pointHoverImage;    
    pointChanged = true;
  }

  if (imageChanged)
  {
      var callBackFunction = function () {
          var f=arguments.callee;
          var map=AdfPage.PAGE.findComponent(f._mapId);          
          var newHTML = map._createFOIImageHTML(f._foi, f._image.width, f._image.height);
          f._foi.setHTMLElement(newHTML);
          f._foi.setWidth(f._image.width);
          f._foi.setHeight(f._image.height);
          f._foi.reDraw();
          f._image = null;
          f._foi = null;
          f._mapId = null;
      };

      var image = new Image();        
      var mapId = this._component.getClientId();

      callBackFunction._image = image;
      callBackFunction._foi = pointFOI;
      callBackFunction._mapId = mapId;
      image.onload = callBackFunction;
      image.src = pointImage;
  }

  // if point did not move, animate locally
  if (!this._pointLocationMoved(pointFOI, longitude, latitude)) {
    this._animatePointFOIUpdate(pointFOI['id'], animationEffect);
    return true;
  }

  // if point did move, call upon spatial to animate the point move
  if (this._movePointFOI(pointFOI, longitude, latitude, animationTime)) {
   return true;
  }
}

AdfDhtmlGeoMapPeer.prototype._animatePointFOIUpdate = function(pointId, animationEffect) {
  if ('a_eff_blink' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'blink');
  }
  else if ('a_eff_blink_n_fade' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'blink');
  }
  else if ('a_eff_fade' == animationEffect) {
    AdfDhtmlGeoMap._animate(pointId, 'fade_out_and_fade_in');
  }
}

AdfDhtmlGeoMapPeer.prototype._getDefaultAnimationTime = function() {
  return 500;
}

AdfDhtmlGeoMapPeer.prototype._getDefaultAnimationEffect = function() {
  return "a_eff_blink";
}

AdfDhtmlGeoMapPeer.prototype._pointLocationMoved = function(pointFOI, newLongitude, newLatitude) {
  if (null == newLongitude && null == newLatitude) {
    return false;
  }
  if (this._getPointLongitude(pointFOI) != newLongitude || 
      this._getPointLatitude(pointFOI) != newLatitude) {
    return true;      
  }  
  return false;
}

AdfDhtmlGeoMapPeer.prototype._movePointFOI = function(pointFOI, newLongitude, 
                                                     newLatitude, animationTime) {
  if (null == newLatitude && null == newLongitude)
    return true;
  
  if (null == newLatitude)
    newLatitude = this._getPointLatitude(pointFOI);
    
  if (null == newLongitude)
    newLongitude = this._getPointLongitude(pointFOI);

  pointFOI.animateToNewLocation(
           MVSdoGeometry.createPoint(newLongitude, newLatitude, this._getInitSrid()), 
           animationTime);
  
  return true;
}
                             
AdfDhtmlGeoMapPeer.prototype._createPointFOI = function(
                             themeId, pointId, pointLabel, longitude, latitude, 
                             dataValue, formattedDataValue, 
                             dataAttrName, dataAttrLabel,
                             pointImage, pointSelectedImage, pointHoverImage, 
                             categoryValue, locationLabelValue) {
    var pointFOI =  this._component._addPointFOI(pointId, longitude, latitude, 
                               pointImage, pointSelectedImage, 
                               dataAttrLabel, formattedDataValue, 
                               locationLabelValue, pointHoverImage, themeId, 
                               categoryValue, dataValue);
    return pointFOI;                             
/*                             
  var pointFOI = MVFOI.createMarkerFOI(
                 pointId, 
                 MVSdoGeometry.createPoint(longitude, latitude, this._getInitSrid()), 
                 pointImage, 5, 5);
                 
  pointFOI['attrnames'] = new Array(dataAttrLabel, '__adf_item_Label0');
  pointFOI['attrs']= new Array(dataValue, formattedDataValue);
  pointFOI['name'] = pointLabel;
  pointFOI.selectedImages = pointSelectedImage;
  pointFOI.originalImages = pointImage;
  pointFOI.hoverImages = pointHoverImage;
  pointFOI._themeID = themeId;        
  
  pointFOI.addEventListener("mouse_click", AdfDhtmlGeoMapPeer._FOIClick);
  if (pointHoverImage != null) {
    var mouseOverFunction = "var elem=document.getElementById('" + pointId + "');elem.src = \"" + pointHoverImage + "\";";
    var mouseOutFunction = "var elem=document.getElementById('" + pointId + "');elem.src = \"" + pointImage + "\";";            
      
    pointFOI.addEventListener("mouse_over", new Function (mouseOverFunction));
    pointFOI.addEventListener("mouse_out", new Function (mouseOutFunction));            
  }
        
  return pointFOI;   
*/
}

/**
 * Override to detach request state change listener
 * @param {AdfUIComponent} component
 * @override
 */
AdfDhtmlGeoMapPeer.prototype.ComponentRemoved = function(component) {

    // Bug 13416899 : increasing memory consumption when using dvt:map component in adf application
    // 
    // rules specified by MapViewer
    // MapViewers recommendation for each case? 
    // 1. Call destroy if the parent div is changed (in our peer's componentRemoved)
    // 2. Optional to call destroy if creating under the same parent div (in our _initMapView
    // The bottom line is that in your component code there is a call to the MVMapVIew constructor like this:
    // var mv =   new MVMapView(<a div>, ...);
    // if each time the above code is invoked, a different div object is passed into it, then you need to make 
    // sure the destroy is called like this:
    // if  when your component is removed the div becomes detached from the dom tree, then we also destroy any
    // mapviewer associated with it (as part of our auto-destroy check).  So that might explain why it works even
    // when you are not calling destroy and using a different div on each refresh.
    // 
    // mapviewer added support for auto destroy to fix this bug and the explicit call to destroy below is to ensure
    // that objects are cleared out.
    // 
    if ( this._component._mapview ) {
       this._component._mapview.removeAllFOIs();
       this._component._mapview.destroy();
       this._component._mapview = null;
    }    
    AdfDhtmlGeoMapPeer.superclass.ComponentRemoved.call(this, component);
}


