
function displayLocationName(data) {
  if (app.options.locationName) {
     for (var prop in data.locationName) {
        var o = data.locationName[prop];
            if (o.type == 'land') {
               var min = 0;
               var max = 5; 
            } else if (o.type == 'region') {
               var min = 4;
               var max = 6;         
            } else if (o.type == 'subregion') {
               var min = 7;
               var max = 9;
            } else if (o.type == 'area') {
               var min = 7;
               var max = 11;          
            }        
        if (!app.markers.locationName[o.location_id] && !(o.loc_x == 0 && o.loc_y == 0)) {
            var icon = new GIcon(app.icons.label, 'markers/l_'+o.location_id+'.png?'+jsonToText(o.title));
            var size = new GSize(((jsonToText(o.title).length*9)+12),20);
            icon.iconSize = size;
            var point =  new GPoint(parseInt(((jsonToText(o.title).length*9)+12)/2),20);
            icon.iconAnchor = point;
            icon.infoWindowAnchor = point;
            if (map.getZoom() >= min && map.getZoom() <= max) {
            if ((isNaN(o.lat) || isNaN(o.lng)) || (o.lng == 0 || o.lat == 0)) {
               var p = coordsToLatLng(o.loc_x, o.loc_y);
            } else {
               var p = new GLatLng(o.lat,o.lng);  
            }  
               var m = new GMarker(p,{'icon': icon, 'title': jsonToText(o.title)});
               m.data = o;
               m.type_id = o.location_id;
               m.detailType = 'Location';
               m.title = jsonToText(o.title);
               m.isMarker = true;
               app.markers.locationName[o.location_id] = m;
               
               map.addOverlay(app.markers.locationName[o.location_id]);
            }
        } else if (app.markers.locationName[o.location_id]) {
         var zm = map.getZoom();
         if (zm < min || zm > max) {
            map.removeOverlay(app.markers.locationName[o.location_id]);
         }
        }
      if (map.getZoom() >= min && map.getZoom() <= max) {
            var pcoords = coordsToText(String(o.loc_x),String(o.loc_y));
            var ptext = pcoords[1].replace('.','p')+pcoords[0].replace('.','p');           
            if (!app.markerCoords[ptext]) app.markerCoords[ptext] = new Array();
            app.markerCoords[ptext].push(app.markers.locationName[o.location_id]);  
      }         
        
     }
  } else {
  	 hideMarkers('locationName');
  } 
}

function displayPOI(data) {

 if (app.options.poi) {
   for (var prop in data.poi) {
      var o = data.poi[prop];
      var min = 8;
      var max = 11;      
      if ($('onlyShowResults') && $('onlyShowResults').checked && !in_results('poi',o.location_id)) {
         if (app.markers.poi[o.location_id]) map.removeOverlay(app.markers.poi[o.location_id]);
         delete(app.markers.poi[o.location_id]);   
         continue; 
      }
      if (!app.markers.poi[o.location_id] && !(o.loc_x == 0 && o.loc_y == 0)) {
         if (map.getZoom() >= min && map.getZoom() <= max) {
            var icon = app.icons.poi;
            if ((isNaN(o.lat) || isNaN(o.lng)) || (o.lng == 0 || o.lat == 0)) {
               var p = coordsToLatLng(o.loc_x, o.loc_y);
            } else {
               var p = new GLatLng(o.lat,o.lng);  
            }
            var m = new GMarker(p,{'icon': icon});
            GEvent.addListener(m,"mouseover", function() {showTooltip(this)});
            GEvent.addListener(m,"mouseout", function() {tooltip.style.visibility="hidden"});             
            m.data = o;
            m.type_id = o.location_id;
            m.detailType = 'Location';
            m.title = jsonToText(o.title);
            m.isMarker = true;
            app.markers.poi[o.location_id] = m;
            map.addOverlay(app.markers.poi[o.location_id]);
         }
      } else if (app.markers.poi[o.location_id]) {
         var zm = map.getZoom();
         if (zm < min || zm > max) {
            map.removeOverlay(app.markers.poi[o.location_id]);
         }
      }
      if (map.getZoom() >= min && map.getZoom() <= max) {
            var pcoords = coordsToText(String(o.loc_x),String(o.loc_y));
            var ptext = pcoords[1].replace('.','p')+pcoords[0].replace('.','p');           
            if (!app.markerCoords[ptext]) app.markerCoords[ptext] = new Array();
            app.markerCoords[ptext].push(app.markers.poi[o.location_id]);  
      } 
      
   }   
 } else {
 	 hideMarkers('poi');
 	}
}

function showLocation(id,dt,loc_x,loc_y) {
   app.typeToShow = (dt) ? 'locationName' : 'poi';
      app.options.locationName = true;
      app.options.poi = true;
      $('f0').firstChild.src = 'on.png';
      $('f1').firstChild.src = 'on.png';
      app.resultToShow = id;
      app.showResult = true;  
   var p = coordsToLatLng(loc_x,loc_y);
   app.forceDisplay = true;
   map.panTo(p);
   
}

function showNPC(id,loc_x,loc_y) {
   app.typeToShow = 'npc';
   app.options.npc = true;
   $(app.optionCheck[app.typeToShow ]).firstChild.src = 'on.png';
   app.resultToShow = id;
   app.showResult = true;  
   var p = coordsToLatLng(loc_x,loc_y);
   app.forceDisplay = true;
   map.panTo(p);
}

function showEnemy(id,loc_x,loc_y) {
   app.typeToShow = 'enemy';
   app.options.enemy = true;
   $(app.optionCheck[app.typeToShow ]).firstChild.src = 'on.png';
   app.resultToShow = id;
   app.showResult = true;  
   var p = coordsToLatLng(loc_x,loc_y);
   app.forceDisplay = true;
   map.panTo(p);
}

function showObject(id,loc_x,loc_y) {
   app.typeToShow = 'object';
   app.options.object = true;
   $(app.optionCheck[app.typeToShow ]).firstChild.src = 'on.png';
   app.resultToShow = id;
   app.showResult = true;  
   var p = coordsToLatLng(loc_x,loc_y);
   app.forceDisplay = true;
   map.panTo(p);
}

function showResource(id,loc_x,loc_y) {
   app.typeToShow = 'resource';
   app.options.resource = true;
   $(app.optionCheck[app.typeToShow ]).firstChild.src = 'on.png';
   app.resultToShow = id;
   app.showResult = true;  
   var p = coordsToLatLng(loc_x,loc_y);
   app.forceDisplay = true;
   map.panTo(p);
}

function showPath(id,loc_x,loc_y) {
   app.typeToShow = 'path';
   app.options.path = true;
   $(app.optionCheck[app.typeToShow ]).firstChild.src = 'on.png';
   app.resultToShow = id;
   app.showResult = true;  
   var p = coordsToLatLng(loc_x,loc_y);
   app.forceDisplay = true;
   map.panTo(p);
}

function toggleRelatedPOI() {
   var o = $('relatedPOI');
   toggleMe(o);
}

function toggleRelatedNPC() {
   var o = $('relatedNPC');
   toggleMe(o);
}

function toggleRelatedEnemy() {
   var o = $('relatedEnemy');
   toggleMe(o);
}

function toggleRelatedObject() {
   var o = $('relatedObject');
   toggleMe(o);
}

function toggleRelatedResource() {
   var o = $('relatedResource');
   toggleMe(o);
}

function toggleRelatedPath() {
   var o = $('relatedPath');
   toggleMe(o);
}


function toggleMe(o) {
   if (o.style.display == '' || o.style.display == 'none') {
      displayBlock(o);
   } else {
      displayNone(o);
   }   
}


function locationInfo(o,m) {
       var coordsArry = coordsToText(o.data[0].loc_x,o.data[0].loc_y);
       var urlTitle = textToURL(o.data[0].title);       
       app.reportMenuCount++;
       $('LocationInfo_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editLocation()>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       +'<table cellspacing=2><tr><td class=infoLabel>Area</td><td class=infoField>'+o.parentName+'</td></tr>'
       +'<tr><td class=infoLabel>Title</td><td class=infoField>'+o.data[0].title+'</td></tr>'
       +'<tr><td class=infoLabel>Description</td><td class=infoField>'+o.data[0].descript+'</td></tr>'
       +'<tr><td class=infoLabel>Location</td><td class=infoField>'+coordsArry[1]+','+coordsArry[0]
       +'<tr><td class=infoLabel>PermaLink</td><td class=infoField><a href=http://www.arda-online.com/map/?Location:'+urlTitle+'_'+m.type_id+'>Link to this entry</a></td></tr>'       
       +'<tr><td class=infoLabel>Added By</td><td class=infoField><a href=http://www.arda-online.com/user.php?id.'+o.creatorID+'>'+o.creatorName+'</a></td></tr>'
       +'</table>';

       var html = '';
       var poiHTML = '';
       for (prop in o.poi) {
          poiHTML += '<div><a href="javascript:showLocation('+o.poi[prop].location_id+','+o.poi[prop].display_type+','+o.poi[prop].loc_x+','+o.poi[prop].loc_y+')">'+o.poi[prop].title+'</a></div>';
       }
       if (poiHTML != '') html += '<div><a href="javascript:toggleRelatedPOI()">Locations</a></div><div id="relatedPOI" class="relatedSubArea">'
       +poiHTML
       +'</div>';
       
       var npcHTML = '';
       for (prop in o.npc) {
          npcHTML += '<div><a href="javascript:showNPC('+o.npc[prop].object_id+','+o.npc[prop].loc_x+','+o.npc[prop].loc_y+')">'+o.npc[prop].title+'</a></div>';
       }
       if (npcHTML != '') html += '<div><a href="javascript:toggleRelatedNPC()">NPCs</a></div><div id="relatedNPC" class="relatedSubArea">'
       +npcHTML
       +'</div>';       
       
       var enemyHTML = '';
       for (prop in o.enemy) {
          enemyHTML += '<div><a href="javascript:showEnemy('+o.enemy[prop].object_id+','+o.enemy[prop].loc_x+','+o.enemy[prop].loc_y+')">'+o.enemy[prop].title+'</a></div>';
       }
       if (enemyHTML != '') html += '<div><a href="javascript:toggleRelatedEnemy()">Enemies</a></div><div id="relatedEnemy" class="relatedSubArea">'
       +enemyHTML
       +'</div>';  
       
       var objectHTML = '';
       for (prop in o.object) {
          objectHTML += '<div><a href="javascript:showObject('+o.object[prop].object_id+','+o.object[prop].loc_x+','+o.object[prop].loc_y+')">'+o.object[prop].title+'</a></div>';
       }
       if (objectHTML != '') html += '<div><a href="javascript:toggleRelatedObject()">Objects</a></div><div id="relatedObject" class="relatedSubArea">'
       +objectHTML
       +'</div>';  
       
       var resourceHTML = '';
       for (prop in o.resource) {
          resourceHTML += '<div><a href="javascript:showResource('+o.resource[prop].object_id+','+o.resource[prop].loc_x+','+o.resource[prop].loc_y+')">'+o.resource[prop].title+'</a></div>';
       }
       if (resourceHTML != '') html += '<div><a href="javascript:toggleRelatedResource()">Resources</a></div><div id="relatedResource" class="relatedSubArea">'
       +resourceHTML
       +'</div>';  
       
       var pathHTML = '';
       for (prop in o.path) {
          pathHTML += '<div><a href="javascript:showPath('+o.path[prop].location_id+','+o.path[prop].loc_x+','+o.path[prop].loc_y+')">'+o.path[prop].title+'</a></div>';
       }
       if (pathHTML != '') html += '<div><a href="javascript:toggleRelatedPath()">Paths</a></div><div id="relatedPath" class="relatedSubArea">'
       +pathHTML
       +'</div>';      
       
       if (html == '') html = 'None'; 
                     
       app.reportMenuCount++;
       $('LocationRelated_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editLocation()>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       +html;
       
       html = '<div class=aCenter><table><tr>';
       var count = 0;
       for (var prop in o.image) {
         var row = o.image[prop];
         if (count == 2) {
            html += '</tr><tr>';  
            count = 0;
         }
         html += '<td><a href=../images/public/'+row.full_src+' target=_blank><img src=../images/public/thumbs/'+row.full_src+' width=125 border=0></a></td>';
         count++;
       }
       html += '</tr></table></div>';
       
       app.reportMenuCount++;
       $('LocationScreenshot_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editLocation()>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       
       var cc = 0;
       var type_id = 'location_id';
       html = '<table id=c_'+type_id+'_'+m.type_id+' width=100%><tbody>';
       for (prop in o.comments) {
         cc++;
         var comment = o.comments[prop];
         var postDate = new Date(comment.timestamp*1000);
         var dateString = postDate.getMonth()+'.'+postDate.getDate()+'.'+postDate.getFullYear()+' '+(postDate.getHours()+1)+':'+postDate.getMinutes();
         html += '<tr><td class=commentText>'+comment.text+'</td></tr>'
         +'<tr><td class=commentInfo>'+comment.user_name+' - '+dateString+'</td></tr>';
       }
       html += '</tbody></table><br><a href="javascript:addComment(\''+type_id+'\','+m.type_id+')">Add a Comment</a>';
       app.reportMenuCount++;
       $('LocationComments_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editLocation()>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       +html;  
      
               
}

function addPOI() {
   app.addType = 'Location';
   if (app.user_id == '0') {
      hideAllMenus();     
      frontAndCenter($(app.addType+'Div'),800,500);
      displayBlock($(app.addType+'Div'));
   } else { 
  // app.adding = true;
  // app.gettingLocation = false;  
   
   app.addPath = 'addLocation.php';
   app.addStart = addLocationStart;
   //app.mapStatus.innerHTML = 'Click the map to add a '+app.addType+'...';
   //displayBlock(app.mapStatus);  
   //hideAllMenus();   
   resetForm('Location');
   app.currentMarker = null;
    addLocationStart();
   }
}

function addLocationStart() {


   var f = document.forms.Location;
      //f.LocationLocXY.value = app.addCoords;
     // f.LocationPoint.value = app.addPoint.toUrlValue(12);      
      //f.LocationZoom.value = map.getZoom();
      f.LocationLocParentText.onkeyup = autoSuggest;
      f.LocationLocParentText.onkeypress = autoSuggest;
      f.LocationLocParentText.onfocus = autoSuggest;
      hideAllMenus();
      frontAndCenter($(app.addType+'Div'),800,500);
   displayBlock($(app.addType+'Div'));
}


function locationSuggest(q) {
	var d = new Date();
         app.autoSuggest.u = 'run/getLocation.php?q='+q+'&d='+d.valueOf();
         app.autoSuggest.returnFunc = getLocationReturn;
         app.autoSuggest.loading = $('LocationLoading');
         app.autoSuggest.drop = $('LocationLocParentDrop');
         app.autoSuggest.idField = document.forms.Location.LocationLocParentID;
         app.autoSuggest.span = $('LocationLocParentSpan');   
         $('LocationLocParentSpan').idField  =  document.forms.Location.LocationLocParentID;
         $('LocationLocParentSpan').textField = document.forms.Location.LocationLocParentText;                
         
}

function submitLocation() {
   var f = document.forms['Location'];
   if (!f.LocationLocParentID.value.match(/[1-9][0-9]*/gi)) {
      alert('Please select a parent area!');
      f.LocationLocParentText.focus();
      return false;
   }
   var v = f.LocationTitle.value;
   if (v == '' || v.match(/[^a-z0-9 '-]/gi)) {
      alert('Please enter a Title. It may only contain letters, numbers, spaces, and the apostrophe.');
      f.LocationTitle.focus();
      return false;
   }
   var postText = preparePost(f);
   var url = 'run/addLocation.php?action=add';
   addPostMessage('Location Submitted!');
   disableMe(f.LocationButton);
   app.editButton = f.LocationButton;
   getRequest(url,'POST',postText,submitLocationReturn);
}

function submitLocationReturn(responseText) {
   enableMe(app.editButton);
   if (!responseText) return false;
   var o = eval(responseText);
   if (o.status) {
      app.gettingLocation = false;  
      app.adding = false;  
      addPostMessage('OK');
      app.typeToShow = (document.forms.Location.LocationType.value == 1) ? 'locationName' : 'poi';
      var id = (app.currentMarker) ? app.currentMarker.type_id : o.new_id;
      if (app.currentMarker && app.markerDetails[app.currentMarker.detailType][app.currentMarker.type_id]) {
      	   delete(app.markerDetails[app.currentMarker.detailType][app.currentMarker.type_id]);
      }
      if (app.currentMarker && app.markers.locationName[app.currentMarker.type_id]) {
         map.removeOverlay(app.markers.locationName[app.currentMarker.type_id]);
         delete(app.markers.locationName[app.currentMarker.type_id]);
         
      } else if (app.currentMarker && app.markers.poi[app.currentMarker.type_id]) {
  
         map.removeOverlay(app.markers.poi[app.currentMarker.type_id]);
         delete(app.markers.poi[app.currentMarker.type_id]); 
      }
      app.currentMarker = null;

      app.options.locationName = true;
      app.options.poi = true;
      resetForm('Location');
      $('f0').firstChild.src = 'on.png';
      $('f1').firstChild.src = 'on.png';
      app.resultToShow = id;
      app.showResult = true;  

      closeAddWindow($("LocationDiv"),true);
   } else {
     addPostMessage('Failed! '+o.error);
   }
}

function getLocationForEdit() {
   hideAllMarkers();
   $('mapStatus').innerHTML = 'Click for new Location...'; 
   displayBlock($('mapStatus'));
   app.gettingLocation = true;   
   map.closeInfoWindow();


   displayNone($(app.addType+'Div'));

   app.editFunction = setNewLocation;
   $('map').firstChild.firstChild.style.cursor = 'crosshair';
   
}

function setNewLocation() {
   var f = document.forms.Location;
   f.LocationLocXY.value = app.editCoords;
   f.LocationPoint.value = app.editPoint.toUrlValue(12);
   displayBlock($(app.addType+'Div'));
}


function editLocation(newLocation) {
    app.addType = 'Location';
    resetForm('Location');
    if (newLocation) {
             var p = app.currentMarker.getPoint();
             var m = new GMarker(p);

             map.addOverlay(m);
             var d = new Date();
             
             var pro = map.getCurrentMapType().getProjection();
             var pnt = pro.fromLatLngToPixel(p,map.getZoom());
             var c = latLngToCoords(pnt,map.getZoom());
             var coords = coordsToText(String(c.x),String(c.y));               
             
             app.editLocationCoords = coords[1]+','+coords[0];
             app.editPoint = p;   
            } else {
             var m = app.currentMarker;
             var o = m.detailData.data[0];
             var coords = coordsToText(String(o.loc_x),String(o.loc_y));   
             app.editLocationCoords = coords[1]+','+coords[0];
             if (o.lat == 0 || o.lng == 0) {
                app.editPoint = coordsToLatLng(o.loc_x,o.loc_y);
             } else {
                app.editPoint = new GLatLng(o.lat,o.lng); 
             }
            }          
            editLocationStart();

}


function editLocationStart() {

      var f = document.forms.Location;
      var m = app.currentMarker;
      var o = m.detailData.data[0];
      f.LocationLocXY.value = app.editLocationCoords;
      f.LocationPoint.value = app.editPoint.toUrlValue(12);
      f.LocationLocParentText.onkeyup = autoSuggest;
      f.LocationLocParentText.onkeypress = autoSuggest;
      f.LocationLocParentText.onfocus = autoSuggest;
      f.LocationUpdateID.value = m.data.location_id;
      f.LocationUpdating.value = 1;
         $('LocationLocParentSpan').idField  =  f.LocationLocParentID;
         $('LocationLocParentSpan').textField = f.LocationLocParentText;     
         displayInline($('LocationLocParentSpan'));  
      f.LocationButton.value = 'Update Location';
      f.LocationLocParentID.value = m.data.location_id_parent;
      displayNone(f.LocationLocParentText);
      app.autoInput = f.LocationLocParentText;
      displayInline($('LocationGetNew'));
      $('LocationLocParentSpan').innerHTML = m.data.parentName+'<img src=cancel.png class=Hand onclick=cancelLocation(this) style=\'padding-left: 3px\'>';
      f.LocationTitle.value = m.title;
      f.LocationDescript.value = m.data.descript;
      setCheckedValue(f.LocationType,o.display_type);
      frontAndCenter($(app.addType+'Div'),800,500);
   displayBlock($(app.addType+'Div'));
}



