
function displayNPC(data) {
 if (app.options.npc) {
   for (var prop in data.npc) {
      var o = data.npc[prop];
      var min = 8;
      var max = 11;
      var zm =  map.getZoom();
      if ($('onlyShowResults') && $('onlyShowResults').checked && !in_results('npc',o.object_id)) {
         if (app.markers.npc[o.object_id]) map.removeOverlay(app.markers.npc[o.object_id]);
         delete(app.markers.npc[o.object_id]);
         continue;
      }
      if (!app.markers.npc[o.object_id] && !(o.loc_x == 0 && o.loc_y == 0)) {
         if (zm >= min && zm <= max) {
            var icon = app.icons.npc;
            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.object_id;
            m.detailType = 'NPC';
            var typeString = (o.type4 != '') ? ' - '+o.type4 : '';
            m.title = jsonToText(o.title+typeString);
            m.isMarker = true;
            app.markers.npc[o.object_id] = m;
            map.addOverlay(app.markers.npc[o.object_id]);
         }
      } else if (app.markers.npc[o.object_id]) {
         if (zm < min || zm > max) {
            map.removeOverlay(app.markers.npc[o.object_id]);
            delete(app.markers.npc[o.object_id]);
         }
      }
      if (zm >= min && zm <= 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.npc[o.object_id]);
      }

   }
 } else {
    hideMarkers('npc');
 }
}

function npcInfo(o,m) {
       var coordsArry = coordsToText(o.data[0].loc_x,o.data[0].loc_y);
       var urlTitle = textToURL(o.data[0].title);
       app.reportMenuCount++;

       var drops = '';
       for (prop in o.drop) {
         var dTitle = textToURL(o.drop[prop].title);
         drops += '<div><a href=http://www.arda-online.com/lotro/item.php?'+dTitle+'_'+o.drop[prop].object_id+' target=_blank>'+o.drop[prop].title+'</a></div>';
       }

       var inacc = (o.data[0].auto_insert == '1') ? '<div class=red>The exact location has not been added yet!</div>' : '';
       $('NPCInfo_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editNPC()>[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>'
       +inacc
       +'<table cellspacing=2><tr><td class=infoLabel>Area</td><td class=infoField>'+o.parentName+'</td></tr>'
       +'<tr><td class=infoLabel>Name</td><td class=infoField>'+o.data[0].title+'</td></tr>'
       +'<tr><td class=infoLabel>Race</td><td class=infoField>'+o.data[0].type2+'</td></tr>'
       +'<tr><td class=infoLabel>Gender</td><td class=infoField>'+o.data[0].type3+'</td></tr>'
       +'<tr><td class=infoLabel>Type</td><td class=infoField>'+o.data[0].type4+'</td></tr>'
       +'<tr><td class=infoLabel>Level</td><td class=infoField>'+o.data[0].lvl+'</td></tr>'
       +'<tr><td class=infoLabel>HP</td><td class=infoField>'+o.data[0].hp+'</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]+'</td></tr>'
       +'<tr><td class=infoLabel>Sells Items</td><td class=infoField>'+drops+'</td></tr>'
       +'<tr><td class=infoLabel>PermaLink</td><td class=infoField><a href=http://www.arda-online.com/map/?NPC:'+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 = 'Related Quests:';
       for (prop in o.quests) {
          var quest = o.quests[prop];
          if (quest.step_order == '1') {
             var action = 'Starts';
          } else if (quest.last_step == '1') {
             var action = 'Finishes';
          } else {
            var action = 'Step '+quest.step_order;
          }
          html += '<div>'+action+': <a href=javascript:getQuestDetails('+quest.quest_id+','+quest.quest_step_id+','+m.type_id+','+m.getPoint().lat()+','+m.getPoint().lng()+')>'+quest.title+'</a></div>';
       }
       app.reportMenuCount++;
       $('NPCRelated_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editNPC()>[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++;
       $('NPCScreenshot_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editNPC()>[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;

       var cc = 0;
       var type_id = 'object_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++;
       $('NPCComments_'+m.type_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editNPC()>[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 addNPC() {
      app.addType = 'NPC';
   if (app.user_id == '0') {
      hideAllMenus();
      frontAndCenter($(app.addType+'Div'),800,500);
      displayBlock($(app.addType+'Div'));
   } else {
   //app.adding = true;

   app.addPath = 'addNPC.php';
   app.addStart = addNPCStart;
   //app.mapStatus.innerHTML = 'Click the map to add a '+app.addType+'...';
   //displayBlock(app.mapStatus);
   //hideAllMenus();
   resetForm('NPC');
   $('NPCDropList').innerHTML = '';
   document.forms.NPC.NPCDrops.value = '';
   app.currentMarker = null;
    addNPCStart();
   }
}

function addNPCStart() {


   var f = document.forms.NPC;
     // f.NPCLocXY.value = app.addCoords;
     // f.NPCPoint.value = app.addPoint.toUrlValue(12);
      f.NPCLocParentText.onkeyup = autoSuggest;
      f.NPCLocParentText.onkeypress = autoSuggest;
      f.NPCLocParentText.onfocus = autoSuggest;

                  hideAllMenus();
      frontAndCenter($(app.addType+'Div'),800,500);
   displayBlock($(app.addType+'Div'));

}

function npcSuggest(q) {
	var d = new Date();
         app.autoSuggest.u = 'run/getLocation.php?q='+q+'&d='+d.valueOf();
         app.autoSuggest.returnFunc = getLocationReturn;
         app.autoSuggest.loading = $('NPCLoading');
         app.autoSuggest.drop = $('NPCLocParentDrop');
         app.autoSuggest.idField = document.forms.NPC.NPCLocParentID;
         app.autoSuggest.span = $('NPCLocParentSpan');
         $('NPCLocParentSpan').idField  =  document.forms.NPC.NPCLocParentID;
         $('NPCLocParentSpan').textField = document.forms.NPC.NPCLocParentText;
}

function submitNPC() {
   var f = document.forms['NPC'];
   if (!f.NPCLocParentID.value.match(/[1-9][0-9]*/gi)) {
      alert('Please select a parent area!');
      f.NPCLocParentText.focus();
      return false;
   }
   var v = f.NPCTitle.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.NPCTitle.focus();
      return false;
   }
   var list = $('NPCDropList');
   var dropList = '';
   var p = '';
   for (var i = 0; i < list.childNodes.length; i++) {
      dropList += p+list.childNodes[i].firstChild.innerHTML;
      p = '|';
   }
   f.NPCDrops.value = dropList;

   var postText = preparePost(f);
   var url = 'run/addNPC.php?action=add';
   addPostMessage('NPC Submitted!');
   disableMe(f.NPCButton);
   app.editButton = f.NPCButton;
   getRequest(url,'POST',postText,submitNPCReturn);
}

function submitNPCReturn(responseText) {
   enableMe(app.editButton);
   if (!responseText) return false;
   var o = eval(responseText);
   if (o.status) {
      app.gettingNPC = false;
      app.adding = false;
      addPostMessage('OK');
      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.npc[app.currentMarker.type_id]) {

         map.removeOverlay(app.markers.npc[app.currentMarker.type_id]);
         delete(app.markers.npc[app.currentMarker.type_id]);
      }
      app.currentMarker = null;
      app.options.npc = true;
      resetForm('NPC');
      $('f2').firstChild.src = 'on.png';
      app.resultToShow = id;
      app.showResult = true;
      app.typeToShow = 'npc';
      closeAddWindow($("NPCDiv"),true);
   } else {
     addPostMessage('Failed! '+o.error);
   }
}


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

      map.closeInfoWindow();


   displayNone($(app.addType+'Div'));
   app.editFunction = setNewLocationNPC;
   $('map').firstChild.firstChild.style.cursor = 'crosshair';


}

function setNewLocationNPC() {
   var f = document.forms.NPC;
   f.NPCLocXY.value = app.editCoords;
   f.NPCPoint.value = app.editPoint.toUrlValue(12);
   displayBlock($(app.addType+'Div'));
}

function editNPC(newLocation) {
    app.addType = 'NPC';
    resetForm('NPC');
    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.editNPCCoords = 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.editNPCCoords = coords[1]+','+coords[0];
             if (o.lat && o.lng) {
                app.editPoint = new GLatLng(o.lat,o.lng);
             } else {
                app.editPoint = coordsToLatLng(o.loc_x,o.loc_y);
             }
            }
             editNPCStart();

}


function editNPCStart() {

      var f = document.forms.NPC;
      var m = app.currentMarker;
      var o = m.detailData.data[0];
      f.NPCLocXY.value = app.editNPCCoords;
      f.NPCPoint.value = app.editPoint.toUrlValue(12);
      f.NPCLocParentText.onkeyup = autoSuggest;
      f.NPCLocParentText.onkeypress = autoSuggest;
      f.NPCLocParentText.onfocus = autoSuggest;
         $('NPCLocParentSpan').idField  =  f.NPCLocParentID;
         $('NPCLocParentSpan').textField = f.NPCLocParentText;
         displayInline($('NPCLocParentSpan'));
      f.NPCUpdateID.value = o.object_id;
      f.NPCUpdating.value = 1;
      f.NPCButton.value = 'Update NPC';
      f.NPCLocParentID.value = o.location_id_parent;
      f.NPCUpdateLocationID.value = o.location_id;
      displayNone(f.NPCLocParentText);
      app.autoInput = f.NPCLocParentText;
      displayInline($('NPCGetNew'));
      $('NPCLocParentSpan').innerHTML = m.data.parentName+'<img src=cancel.png class=Hand onclick=cancelLocation(this) style=\'padding-left: 3px\'>';
      f.NPCTitle.value = o.title;
      f.NPCRace.value = o.type2;
      f.NPCGender.value = o.type3;
      f.NPCType.value = o.type4;
      f.NPCLevel.value = o.lvl;
      f.NPCHP.value = o.hp;
      f.NPCDescript.value = o.descript;

      $('NPCDropList').innerHTML = '';
       for (prop in m.detailData.drop) {
         f.NPCDrop.value = m.detailData.drop[prop].title;
         npcAddDrop();
       }

         frontAndCenter($(app.addType+'Div'),800,500);
   displayBlock($(app.addType+'Div'));
}


function npcAddDrop() {
   var f = document.forms.NPC;
   var list = $('NPCDropList');
   var inp = f.NPCDrop;
   var v = inp.value.replace(/|/g,'');
   if (v == '') return false;
   var html = '<div><span>'+v+'</span><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=cancel.png class=Hand onclick=cancelEnemyDrop(this)></span></div>';
   list.innerHTML += html;
   inp.value = '';
}

function cancelNPCDrop(o) {
   o.parentNode.parentNode.parentNode.removeChild(o.parentNode.parentNode);
}
