
function displayQuest(data) {
   if (!app.options.quest) {
      hideMarkers('quest'); 
      return false;
   }
   app.questData = new Array();
   for (prop in data.quest) {
      if ($('onlyShowResults') && $('onlyShowResults').checked && !in_results('quest',data.quest[prop].quest_id)) continue;       
      app.questData.push(data.quest[prop]);
   }
   var quests = new Array();
   for (prop in app.markers.npc) {
      var o = app.markers.npc[prop];
      if (in_objectArry(o.type_id,app.questData)) quests.push(o);
   }
   for (prop in app.markers.enemy) {
      var o = app.markers.enemy[prop];
      if (in_objectArry(o.type_id,app.questData)) quests.push(o);
   }
   for (prop in app.markers.object) {
      var o = app.markers.object[prop];
      if (in_objectArry(o.type_id,app.questData)) quests.push(o);
   }      
   for (var i = 0; i < quests.length; i++) {   
      var o = quests[i];
      var min = 8;
      var max = 11;  
      var zm =  map.getZoom();   
      if (!app.markers.quest[o.type_id]) { 
         if (zm >= min && zm <= max) {
            var icon = app.icons.quest;
            var p = o.getPoint();
            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.quest_id = o.quest_id;
            m.type_id = o.type_id;
            m.detailType = 'Quest';
            var title = '';
            for (var i1 = 0; i1 < app.questData.length; i1++) {
               var quest = app.questData[i1];
               if (quest.object_id == o.type_id) {
                  if (quest.step_order == 1) {
                     var text = 'Starts quest: '+jsonToText(quest.title);
                  } else if (quest.last_step == '1') {
                     var text = 'Finishes quest: '+jsonToText(quest.title);
                  } else {
                     var text = 'Step '+quest.step_order+' for quest: '+jsonToText(quest.title); 
                  }
                  title += '<div>'+text+'</div>'
               }
            }
            
            m.title = title;
            m.isMarker = true;
            app.markers.quest[o.type_id] = m;
            map.addOverlay(app.markers.quest[o.type_id]);      
         }
      } else if (app.markers.quest[o.type_id]) {
         if (zm < min && zm > max) {
            map.removeOverlay(app.markers.quest[o.type_id]);
         }
      }
      
      
   }
   
   if (app.questIDToShow != 0 && app.questStepIDToShow != 0 && app.markers.quest[app.questObjectIDToShow]) {
      app.getMarkerDetail = app.markers.quest[app.questObjectIDToShow];
      getQuestDetails(app.questIDToShow,app.questStepIDToShow);     
      app.questIDToShow = 0;
      app.questStepIDToShow = 0;  
      app.questObjectIDToShow = 0;
      app.typeToShow = '';
      app.resultToShow = 0;
      app.showResult = false;      
   }
      
}

function questListInfo(m) {
       var html = '<div><b>Select a Quest:</b></div>';         
       var listedQuests = new Array();   
       var listedQuestSteps = new Array(); 
            for (var i1 = 0; i1 < app.questData.length; i1++) {
               var quest = app.questData[i1];
               if (quest.object_id == m.type_id) {
                  if (!in_array(quest.quest_id,listedQuests)) {
                     html += '<div class=m20><a href="javascript:getQuestDetails('+quest.quest_id+','+quest.quest_step_id+')">'+jsonToText(quest.title)+'</a></div>';
                     listedQuests.push(quest.quest_id);
                     listedQuestSteps.push(quest.quest_step_id);
                  }
               }
            }
            
         if (listedQuests.length == 1) {
            getQuestDetails(listedQuests[0],listedQuestSteps[0]);
            return false;
         }
       
          var infoTabs = [
             new GInfoWindowTab('Related Quests', '<div class=infoWindow id='+m.detailType+'Info_'+m.type_id+'>'+html+'</div>')

          ];
          m.openInfoWindowTabsHtml(infoTabs);  
       

}

function selectQuest() {
         $('f4').firstChild.src = 'on.png'
         app.options.quest = true;
         app.options.enemy = true;
         $('f3').firstChild.src = 'on.png'
         app.options.npc = true;
         $('f2').firstChild.src = 'on.png'
         app.options.object = true;
         $('f5').firstChild.src = 'on.png'      
}

function getQuestDetails(quest_id,step_id,object_id,lat,lng) {
   if (!app.options.quest) {
      selectQuest();
   }
   
   map.closeInfoWindow();
   if (app.questPolylines) {
      for (prop in app.questPolylines) {
         map.removeOverlay(app.questPolylines[prop]);
         delete(app.questPolylines[prop]);
      }
   }   
   hideMarkers('path');
   $('f8').firstChild.src = 'off.png';
   app.options.path = false;   
   if (object_id && !app.markers.quest[object_id]) {
      app.questIDToShow = quest_id;
      app.questStepIDToShow = step_id;
      app.questObjectIDToShow = object_id;
      
      if (!lat || !lng) {
         app.showQuestStep = step_id;
         app.last_quest_id = quest_id;   
         if (app.markerDetails['Quest'][quest_id]) {
            getQuestDetailReturn(app.markerDetails['Quest'][quest_id]);
         } else {
            var d = new Date();
            getRequest('run/getQuestDetail.php?id='+quest_id+'&d='+d.valueOf(),'GET','',getQuestDetailReturn);
         }
      } else if (lat != 0 && lng != 0) {
         
         map.panTo(new GLatLng(lat,lng));
         displayMarkers();
      }
   } else {
      if (object_id && app.markers.quest[object_id]) {
         app.getMarkerDetail = app.markers.quest[object_id];
      }
      var m = app.getMarkerDetail;
          var infoTabs = [
             new GInfoWindowTab('Quest Step', '<div class=infoWindow id='+m.detailType+'Step_'+step_id+'><img src=loading.gif> Loading...</div>'),
             new GInfoWindowTab('Quest', '<div class=infoWindow id='+m.detailType+'Info_'+step_id+'><img src=loading.gif> Loading...</div>'),
             new GInfoWindowTab('Screenshots', '<div class=infoWindow id='+m.detailType+'Screenshot_'+step_id+'><img src=loading.gif> Loading...</div>'),
             new GInfoWindowTab('Comments', '<div class=infoWindow id='+m.detailType+'Comments_'+quest_id+'><img src=loading.gif> Loading...</div>')             
          ];
      m.openInfoWindowTabsHtml(infoTabs);     
      app.showQuestStep = step_id;
      app.last_quest_id = quest_id;   
      if (app.markerDetails[m.detailType][quest_id]) {
         getQuestDetailReturn(app.markerDetails[m.detailType][quest_id]);
      } else {
         var d = new Date();
         getRequest('run/getQuestDetail.php?id='+quest_id+'&d='+d.valueOf(),'GET','',getQuestDetailReturn);
      }
   }
   
}

function getQuestDetailReturn(responseText) {
   var o = eval(responseText);
   app.markerDetails['Quest'][app.last_quest_id] = responseText;
   //draw paths between objects
   
   if (!$('QuestInfo_'+app.showQuestStep)) {
      
     if (!o.objectives[app.questStepIDToShow]) {
        for (prop in o.objectives) {
           var firstObj = o.objectives[prop][0];
           break; 
        } 
     } else {
        var firstObj = o.objectives[app.questStepIDToShow][0];
     }
     app.questObjectIDToShow = firstObj.object_id;
     if (firstObj.loc_x && firstObj.loc_y) {    
        var p = coordsToLatLng(firstObj.loc_x,firstObj.loc_y);  
        map.panTo(p);
        displayMarkers();
        return false;
     } else {
         var m = app.getMarkerDetail;
          var infoTabs = [
             new GInfoWindowTab('Quest Step', '<div class=infoWindow id=QuestStep_'+app.questStepIDToShow+'><img src=loading.gif> Loading...</div>'),
             new GInfoWindowTab('Quest', '<div class=infoWindow id=QuestInfo_'+app.questStepIDToShow+'><img src=loading.gif> Loading...</div>'),
             new GInfoWindowTab('Screenshots', '<div class=infoWindow id=QuestScreenshot_'+app.questStepIDToShow+'><img src=loading.gif> Loading...</div>'),
             new GInfoWindowTab('Comments', '<div class=infoWindow id=QuestComments_'+app.last_quest_id+'><img src=loading.gif> Loading...</div>')             
          ];
         m.openInfoWindowTabsHtml(infoTabs); 
     }
     
   }   
   
   if (app.questPolylines) {
      for (prop in app.questPolylines) {
         map.removeOverlay(app.questPolylines[prop]);
         delete(app.questPolylines[prop]);
      }
   } else {
      app.questPolylines = new Object();
   }   
   app.drawnQuestLines = new Object();
   if (o.paths) {
      for (prop in o.paths) {
         var path = o.paths[prop][0];
         var location_id = path.location_id;
         if (app.questPolylines[location_id]) continue;
         
         var pointsTextArry = path.poly_geo.split('|');
         
         var points = new Array();
         for (var i1 = 0; i1 < pointsTextArry.length; i1++) {
            var latlng = pointsTextArry[i1].split(',');
            var lat = latlng[0];
            var lng = latlng[1];
            points.push(new GLatLng(lat,lng));
         }
         var polyline = new GPolyline(points, "#ff0000", 5);
         polyline.idtext = prop;
         app.drawnQuestLines[prop] = true;
         app.questPolylines[location_id] = polyline;
         //app.getMarkerDetail.polyline = app.questPolylines[location_id];
         map.addOverlay(app.questPolylines[location_id]);
      }
   }
   var last_object_id = 0;
   for (prop in o.objectives) {
      var obj = o.objectives[prop][0];
      object_id = obj.object_id;
      if (app.drawnQuestLines['s'+last_object_id+'e'+object_id] || app.drawnQuestLines['s'+object_id+'e'+last_object_id]) {
         last_object_id = object_id;
         continue;
      }
      if (last_object_id != 0) {
            if ((isNaN(last_object.lat) || isNaN(last_object.lng)) || (last_object.lng == 0 || last_object.lat == 0)) {
               var p1 = coordsToLatLng(last_object.loc_x, last_object.loc_y);
            } else {
               var p1 = new GLatLng(last_object.lat,last_object.lng);  
            }
            if ((isNaN(obj.lat) || isNaN(obj.lng)) || (obj.lng == 0 || obj.lat == 0)) {
               var p2 = coordsToLatLng(obj.loc_x, obj.loc_y);
            } else {
               var p2 = new GLatLng(obj.lat,obj.lng);  
            }                    
         var points = new Array(p1,p2);
         var polyline = new GPolyline(points, "#ff0000", 5);
         app.drawnQuestLines['s'+last_object_id+'e'+object_id] = true;
         app.questPolylines['s'+last_object_id+'e'+object_id] = polyline;
         //app.getMarkerDetail.polyline = app.questPolylines[obj.location_id];
         map.addOverlay(app.questPolylines['s'+last_object_id+'e'+object_id]);
      } else {
         last_object_id = object_id;
         last_object = obj;
      }
   }



   var q = o.quest[0];
   var urlTitle = textToURL(q.title);   
   //fill info boxes
   app.reportMenuCount++;
   var parentText = (q.quest_id_parent) ? '<a href="javascript:getQuestDetails('+q.quest_id_parent+',1,1)">'+q.parent_title+'</a>' : 'None';
   var childText = (q.quest_id_child) ? '<a href="javascript:getQuestDetails('+q.quest_id_child+',1,1)">'+q.child_title+'</a>' : 'None';
   
   
   var c = 0;
   var rw = '';
   for (prop in o.reward) {
      var rwObj = o.reward[prop];
      var count = (rwObj.quantity > 1) ? ' ('+rwObj.quantity+')': '';
      rw += '<div>'+rwObj.object_title+count+'</a></div>';
      c++;
   }
   var rwRelText = (c > 0) ? '<tr><td class=infoLabel valign=top>Quest Rewards</td><td class=infoField valign=top>'+rw+'</td></tr>' : '';   
   
   var c = 0;
   var rq = '';
   for (prop in o.related_quests) {
      var rqObj = o.related_quests[prop];
      rq += '<div><a href="javascript:getQuestDetails('+q.quest_id_rel+',1,1)">'+rqObj.name+'</a></div>';
      c++;
   }
   var qRelText = (c > 0) ? '<tr><td class=infoLabel valign=top>Related Quests</td><td class=infoField valign=top>'+rq+'</td></tr>' : '';
   
   var c = 0;
   var rd = '';
   for (prop in o.related_deeds) {
      var rdObj = o.related_deeds[prop];
      rd += '<div>'+rdObj.name+'</div>';
      c++;
   }
   var dRelText = (c > 0) ? '<tr><td class=infoLabel valign=top>Related Deeds</td><td class=infoField valign=top>'+rd+'</td></tr>' : '';
   
   
   var fellowText = (q.fellowship == '1') ? '<tr><td class=infoLabel>Fellowship</td><td class=infoField>'+BtoT(q.fellowship)+'</td></tr>' : '';
   var repeatText = (q.repeatable == '1') ? '<tr><td class=infoLabel>Repeatable</td><td class=infoField>'+BtoT(q.repeatable)+'</td></tr>' : '';
   var instanceText = (q.instance == '1') ? '<tr><td class=infoLabel>Instance</td><td class=infoField>'+BtoT(q.instance)+'</td></tr>' : '';

   
   //
   var html = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editQuest('+app.last_quest_id+')>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+','+app.last_quest_id+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       +'<table><tr><td class=infoLabel>Area</td><td class=infoField>'+q.heading+'</td></tr>'
       +'<tr><td class=infoLabel>Name</td><td class=infoField>'+q.title+'</td></tr>'
       +'<tr><td class=infoLabel>Prerequisite</td><td class=infoField>'+parentText+'</td></tr>'
       +'<tr><td class=infoLabel>Next Quest</td><td class=infoField>'+childText+'</td></tr>'
       +'<tr><td class=infoLabel>Official Level</td><td class=infoField>'+q.lvl+'</td></tr>'
       +'<tr><td class=infoLabel>Recommended Level</td><td class=infoField>'+q.min_lvl+'</td></tr>'
       +'<tr><td class=infoLabel>Description</td><td class=infoField>'+q.descript+'</td></tr>'
       +fellowText
       +repeatText
       +instanceText
       +rwRelText
       +qRelText
       +dRelText
       +'<tr><td class=infoLabel>PermaLink</td><td class=infoField><a href=http://www.arda-online.com/map/?Quest:'+urlTitle+'_'+q.quest_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>';
   




   app.reportMenuCount++;
   $('QuestInfo_'+app.showQuestStep).innerHTML = html;
   //<a href=javascript:editQuest()>[edit]</a> | 
   var html = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editQuest('+app.last_quest_id+')>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+','+app.last_quest_id+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       +'<table><tr><td colspan=2 class=infoLabel>'+q.title+'</td></tr>';
       
       var qsteps = o.quest_steps;
       for (prop in qsteps) {
          var step = qsteps[prop];
            if (step.step_order == 1) {
               var stepText = 'Start';
            } else if (step.last_step == 1) {
               var stepText = 'Finish';
            } else {
               var stepText = 'Step '+(step.step_order-1);
            }          
          if (step.quest_step_id == app.showQuestStep) {
            html += '<tr><td colspan=2 class=m20><div><b>'+stepText+'</b></div>'
            +'<table><tr><td  class=infoLabel>Title</td><td class=infoField>'+step.title+'</td></tr>'
            +'<tr><td  class=infoLabel>Dialog</td><td class=infoField>'+step.dialog+'</td></tr>'
            +'<tr><td  class=infoLabel>Comments</td><td class=infoField>'+step.descript+'</td></tr>'
            +'<tr><td  class=infoLabel>Objectives</td><td class=infoField>';
            for (prop1 in o.objectives) {
               var thisObj = o.objectives[prop1][0];
               if (thisObj.type_id == app.showQuestStep) {
                  var quant = (thisObj.quantity > 1) ? ' ('+thisObj.quantity+')' : '';
                  html += '<li>'+thisObj.value+': '+thisObj.object_title+quant+'</li>';
               }
            }
            
            
            html += '</td></tr></table></td></tr>';
            

          } else {
             //if (step.quest_step_id == app.showQuestStep) {     
                for (prop1 in o.objectives) {
                   var thisObj = o.objectives[prop1][0];
                   if (thisObj.type_id == step.quest_step_id) {                      
                      var object_id = thisObj.object_id;
                      var lat = thisObj.lat;
                      var lng = thisObj.lng;
                      break;
                   }
                }
            // }
            if (lat && lng) {
               html += '<tr><td colspan=2 class=m20><b>'+stepText+'</b>: <a href="javascript:getQuestDetails('+app.last_quest_id+','+step.quest_step_id+','+object_id+','+lat+','+lng+')">'+step.title+'</a></td></tr>';
            } else {
               html += '<tr><td colspan=2 class=m20><b>'+stepText+'</b>: <a href="javascript:getQuestDetails('+app.last_quest_id+','+step.quest_step_id+','+object_id+')">'+step.title+'</a></td></tr>';
            }
          }
         }
       html += '</table><br><br>';
   
   $('QuestStep_'+app.showQuestStep).innerHTML = html;
       
       var cc = 0;
       var type_id = 'quest_id';
       html = '<table id=c_'+type_id+'_'+app.last_quest_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+'\','+app.last_quest_id+')">Add a Comment</a>';
       app.reportMenuCount++;
       //<a href=javascript:editQuest()>[edit]</a> | 
       $('QuestComments_'+app.last_quest_id).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
       +'<a href=javascript:editQuest('+app.last_quest_id+')>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+','+app.last_quest_id+')">[report]</a>'
       +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
       +html;   
       
   
       
       var im = o.image;
       if (im[app.showQuestStep]) {
          var m = im[app.showQuestStep];
          html = '<div class=aCenter><table><tr>';
          var count = 0;
          for (var prop in m) {
             var row = m[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++;
           //<a href=javascript:editNPC()>[edit]</a> | 
           if ($('QuestScreenshot_'+app.showQuestStep)) {
              $('QuestScreenshot_'+app.showQuestStep).innerHTML = '<div><table width=100%><tbody><tr><td width=65%></td><td width=35% class=aRight>'
              +'<a href=javascript:editQuest('+app.last_quest_id+')>[edit]</a> | <a href="javascript:reportEntryMenu('+app.reportMenuCount+','+app.last_quest_id+')">[report]</a>'
              +'</td></tr><tr><td></td><td><div class=Dnone id=rm'+app.reportMenuCount+'></div></td></tr></tbody></table></div>'
              +html;           
           }
      } else {
         if ($('QuestScreenshot_'+app.showQuestStep)) $('QuestScreenshot_'+app.showQuestStep).innerHTML = '';
      }
       
   
}

function BtoT(v) {
   return (v == '1') ? "Yes" : "No";
}

function addQuest() {
      app.addType = 'Quest';
   if (app.user_id == '0') {
      hideAllMenus();     
      frontAndCenter($(app.addType+'Div'),800,500);
      displayBlock($(app.addType+'Div'));
   }  else {
   resetQuestForm();
    var f = document.forms.Quest;
    app.questUse = f.QuestObjUseText;
    app.questUse.onkeypress = autoSuggest;
    app.questUse.onkeyup = autoSuggest;
    app.questUse.onfocus = function() {
       if (app.questUse.value == 'Search...') {
         app.questUse.value = '';
         app.questUse.style.fontStyle = 'normal'; 
      }
     }
    app.questUse.onblur = function() {
       if (app.questUse.value == '') {
         app.questUse.value = 'Search...';
         app.questUse.style.fontStyle = 'italic';   
       }       
     }   
    app.questGetItem = f.QuestGetItemText;
    app.questGetItem.onkeypress = autoSuggest;
    app.questGetItem.onkeyup = autoSuggest;
    app.questGetItem.onfocus = function() {
       if (app.questGetItem.value == 'Search...') {
         app.questGetItem.value = '';
         app.questGetItem.style.fontStyle = 'normal'; 
      }
     }
    app.questGetItem.onblur = function() {
       if (app.questGetItem.value == '') {
         app.questGetItem.value = 'Search...';
         app.questGetItem.style.fontStyle = 'italic';   
       }       
     }   
    app.questGetItemLoc = f.QuestGetItemLocText;
    app.questGetItemLoc.onkeypress = autoSuggest;
    app.questGetItemLoc.onkeyup = autoSuggest;
    app.questGetItemLoc.onfocus = function() {
       if (app.questGetItemLoc.value == 'Search...') {
         app.questGetItemLoc.value = '';
         app.questGetItemLoc.style.fontStyle = 'normal'; 
      }
     }
    app.questGetItemLoc.onblur = function() {
       if (app.questGetItemLoc.value == '') {
         app.questGetItemLoc.value = 'Search...';
         app.questGetItemLoc.style.fontStyle = 'italic';   
       }       
     }  
   
//   attachHelp($('addQuestArea'));
   app.questObjectiveCount = 0;

   hideAllMenus();
   f.QuestUpdateID.value = 0;
   f.QuestUpdating.value = 0;   
   frontAndCenter($(app.addType+'Div'),800,500);
   displayBlock($(app.addType+'Div'));   
  }
}


function questUseSuggest(q) {
	var d = new Date();
	var f = document.forms['Quest'];
	var type = f.QuestObjType.value;
	if (type == 'Kill Enemy by Name') {
	   type = 'Enemy';
	} else if (type == 'Kill Enemy by Type') {
	   type = 'EnemyType';
	} else if (type == 'Talk to NPC' || type == 'Protect NPC') {
	   type = 'NPC';
	} else if (type == 'Collect Item') {
	   type = 'item';	   
	} else {
	   type = 'Object';
	}
         app.autoSuggest.u = 'run/get'+type+'.php?q='+q+'&d='+d.valueOf();
         app.autoSuggest.returnFunc = getLocationReturn;
         app.autoSuggest.loading = $('QuestObjUseTextLoading');
         app.autoSuggest.drop = $('QuestObjUseTextDrop');
         app.autoSuggest.idField = document.forms.Quest.QuestObjUseID;
         app.autoSuggest.span = $('QuestObjUseTextSpan');  
         app.autoSuggest.addAsNew = true;
         $('QuestObjUseTextSpan').idField  =  f.QuestObjUseID;
         $('QuestObjUseTextSpan').textField = f.QuestObjUseText;            
         app.autoSuggest.col2 = true;
         app.autoSuggest.col2FieldName = 'location_name';
}


function questGetItemSuggest(q) {
	var d = new Date();
	var f = document.forms['Quest'];
	var type = f.QuestCollectItemType.value;
	if (type == 'Enemy by Name') {
	   type = 'Enemy';
	} else if (type == 'Enemy by Type') {
	   type = 'EnemyType';
	} else {
	   type = 'Object';
	}
         app.autoSuggest.u = 'run/get'+type+'.php?q='+q+'&d='+d.valueOf();
         app.autoSuggest.returnFunc = getLocationReturn;
         app.autoSuggest.loading = $('QuestGetItemTextLoading');
         app.autoSuggest.drop = $('QuestGetItemTextDrop');
         app.autoSuggest.idField = f.QuestGetItemID;
         app.autoSuggest.span = $('QuestGetItemTextSpan');  
         app.autoSuggest.addAsNew = true;
         $('QuestGetItemTextSpan').idField  =  f.QuestGetItemID;
         $('QuestGetItemTextSpan').textField = f.QuestGetItemText;            
         app.autoSuggest.col2 = true;
         app.autoSuggest.col2FieldName = 'location_name';
         app.autoSuggest.col2IDFieldName = 'location_id_parent';
         app.autoSuggest.runOnSelect = questSelectItem;
         
}

function questGetItemLocSuggest(q) {
	var d = new Date();
	var f = document.forms['Quest'];
         app.autoSuggest.u = 'run/getLocation.php?q='+q+'&d='+d.valueOf();
         app.autoSuggest.returnFunc = getLocationReturn;
         app.autoSuggest.loading = $('QuestGetItemLocTextLoading');
         app.autoSuggest.drop = $('QuestGetItemLocTextDrop');
         app.autoSuggest.idField = f.QuestGetItemLocID;
         app.autoSuggest.span = $('QuestGetItemLocTextSpan');  
         app.autoSuggest.addAsNew = false;
         $('QuestGetItemLocTextSpan').idField  =  f.QuestGetItemLocID;
         $('QuestGetItemLocTextSpan').textField = f.QuestGetItemLocText;            
         app.autoSuggest.col2 = true;
         app.autoSuggest.col2FieldName = 'location_name_parent';
         app.autoSuggest.col2IDFieldName = 'location_id_parent';

         
}


function submitQuest() {
   var f = document.forms['Quest'];

   //var v = f.QuestTitle.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.QuestTitle.focus();
   //   return false;
   //}
   
   var rewardText = '';
   var list = $('QuestRewardList');
   var c = '';
   for (var i = 0; i < list.childNodes.length; i++) {
      var o = list.childNodes[i];
      rewardText += c+o.firstChild.innerHTML; 
      c = '|';  
   }
   
   f.QuestRewards.value = rewardText;
   
   var relatedText = '';
   var list = $('QuestRelatedList');
   var c = '';
   for (var i = 0; i < list.childNodes.length; i++) {
      var o = list.childNodes[i];
      relatedText += c+o.firstChild.innerHTML;   
      c = '|';
   }
   
   f.QuestRelated.value = relatedText;   
   
   var stepText = '';
   var objectiveText = '';
   var list = $('QuestStepList');
   var c = '';
   for (var i = 0; i < list.childNodes.length; i++) {
      var o = list.childNodes[i];
      var title = (o.childNodes[0].innerHTML == '') ? 'Step '+(i+1) : o.childNodes[0].innerHTML;
      var desc = (o.childNodes[1].innerHTML == '') ? 'Step '+(i+1) : o.childNodes[1].innerHTML;
      var dialog = (o.childNodes[2].innerHTML == '') ? 'No Dialog Entered' : o.childNodes[2].innerHTML;
      var idValue = o.childNodes[4].innerHTML;
      stepText += c+title+':'+desc+':'+dialog+':'+idValue;
      var stepObjectiveList = o.childNodes[3];
      var c2 = '';
      objectiveText = objectiveText+c;
      for (var i1 = 0; i1 < stepObjectiveList.childNodes.length; i1++) {
         var objective = stepObjectiveList.childNodes[i1];
         objectiveText += c2+objective.firstChild.innerHTML+':'+objective.childNodes[1].innerHTML+':'+objective.childNodes[2].innerHTML;
         c2 = ';';
      }
      c = '|';
   }
   
   f.QuestSteps.value = stepText;
   f.QuestObjectives.value = objectiveText;

   var postText = preparePost(f);
   var url = 'run/addQuest.php?action=add';
   addPostMessage('Quest Submitted!');
   disableMe(f.QuestButton);
   app.editButton = f.QuestButton;
   getRequest(url,'POST',postText,submitQuestReturn);
}

function submitQuestReturn(responseText) {
   enableMe(app.editButton);
   if (!responseText) return false;
   var o = eval(responseText);
   if (o.status) {
      app.gettingQuest = false;  
      addPostMessage('OK');
      resetQuestForm();
      if (app.markerDetails['Quest'][o.new_id]) delete(app.markerDetails['Quest'][o.new_id]);
   } else {
     addPostMessage('Failed! '+o.error);
   }
}

function resetQuestForm() {
   var f = document.forms['Quest'];
   f.reset();
   $('QuestObjectiveList').innerHTML = '';
   $('QuestRelatedList').innerHTML = '';
   $('QuestRewardList').innerHTML = '';
   $('QuestStepList').innerHTML = '';
   questStepCancel();
   f.QuestUpdateID.value = 0;
   f.QuestUpdating.value = 0;
   app.questObjectiveCount = 0;
   app.questStepCount = 0;
}

//function getQuestForEdit() {
//   hideAllMarkers();
//   $('mapStatus').innerHTML = 'Click for new Quest Location...'; 
//   displayBlock($('mapStatus'));
//   app.gettingLocation = true;
//   map.closeInfoWindow();
//   app.editFunction = editQuest;
//}

function editQuest(id) {
   addQuest();
   editQuestStart(id);
}


function editQuestStart(id) {

      var f = document.forms.Quest;
      var o = eval(app.markerDetails['Quest'][id]);
      f.QuestUpdateID.value = id;
      f.QuestUpdating.value = 1;
      f.QuestButton.value = 'Update Quest';
      
      var q = o.quest[0];
      f.QuestTitle.value = jsonToText(q.title);
      f.QuestHeading.value = q.heading;
      f.QuestDescript.value = jsonToText(q.descript);
      f.QuestLvl.value = q.lvl;
      f.QuestMinLvl.value = q.min_lvl
      f.QuestMoneyReward.value = q.reward;

      f.QuestRepeatable.checked = (q.repeatable == '1') ? true : false;
      f.QuestFellowship.checked = (q.fellowship == '1') ? true : false;
      f.QuestInstance.checked = (q.instance == '1') ? true : false;
      f.QuestPrereqText.value = jsonToText(q.parent_title);

      for (prop in o.rewards) {
         var rw = o.rewards[prop][0];
         f.QuestSelectable.checked = (rw.comment == 'true') ? true : false;
         f.QuestRewardCount.value = rw.quantity;
         f.QuestReward.value = jsonToText(rw.object_title);
         addQuestReward(f);
      }

      for (prop in o.related_quests) {
         var rq = o.related_quests[prop][0];
         f.QuestRelatedType.value = 'Quest';
         f.QuestRelatedText.value = jsonToText(rq.object_title);
         f.QuestRelatedComment.value = jsonToText(rq.comment);   
         addQuestRelated(f);   
      }
      
      for (prop in o.related_deeds) {
         var rd = o.related_quests[prop][0];
         f.QuestRelatedType.value = 'Deed';
         f.QuestRelatedText.value = jsonToText(rd.object_title);
         f.QuestRelatedComment.value = jsonToText(rd.comment);
         addQuestRelated(f);      
      }      
      
      for (stepprop in o.quest_steps) {
         var step = o.quest_steps[stepprop];
         f.QuestStepTitle.value = jsonToText(step.title);
         f.QuestStepDialog.value = jsonToText(step.dialog);
         f.QuestStepDescript.value = jsonToText(step.descript);
         f.QuestStepID.value = step.quest_step_id;
         app.questStepToEdit = step.quest_step_id;
         
         for (prop in o.objectives[step.quest_step_id]) {
            var obj = o.objectives[step.quest_step_id][prop];
            f.QuestObjType.value = obj.value;
            f.QuestObjUseID.value = (obj.value == 'Collect Item')? obj.item_id : obj.object_id;
            $('QuestObjUseTextSpan').innerHTML = '<span>'+obj.object_title+'</span>';
            f.QuestObjUseNumber.value = obj.quantity;
            if (obj.value == 'Collect Item') {
               f.QuestCollectItemType.value = obj.comment_rel;
               f.QuestGetItemID.value = obj.object_id;
               $('QuestGetItemTextSpan').innerHTML = '<span>'+obj.object_title_rel+'</span>';

               f.QuestGetItemLocID.value = obj.location_id;
               $('QuestGetItemLocTextSpan').innerHTML = '<span>'+obj.location_title+'</span>';
            }
            addQuestObjective();
         }
         addQuestStep(true);
      }
      

}

function addQuestObjective() {
      var f = document.forms.Quest;
      var list = $('QuestObjectiveList');
      var textvalue = $('QuestObjUseTextSpan').firstChild.innerHTML.replace(/[|:;]/g,'');
      var idvalue = f.QuestObjUseID.value;
      if (textvalue == '') return false;
      var intvalue = f.QuestObjUseNumber.value.replace(/[^0-9]/g,'');
      if (intvalue == '') return false;
      //var loc = f.QuestObjUseLocation.value.replace(/[|:;]/g,'');
      var intText = (intvalue > 1) ? ' ('+intvalue+')' : '';
      
      var itemType = f.QuestCollectItemType.value;
      var itemName = ($('QuestGetItemTextSpan').firstChild) ? $('QuestGetItemTextSpan').firstChild.innerHTML.replace(/[|:;]/g,'') : '';
      var itemID = f.QuestGetItemID.value;
      var itemLocName = ($('QuestGetItemLocTextSpan').firstChild) ? $('QuestGetItemLocTextSpan').firstChild.innerHTML : '';
      var itemLocID = f.QuestGetItemLocID.value;
      
      list.innerHTML += '<div><span class=dNone>'+f.QuestObjType.value+':'+textvalue+':'+intvalue+':'+idvalue+'</span>'
      +'<span class=dNone>'+f.QuestImageSrc.value+':'+f.QuestImageId.value+'</span>'
      +'<span class=dNone>'+itemType+':'+itemName+':'+itemID+':'+itemLocName+':'+itemLocID+'</span>'
      +'<span>'+f.QuestObjType.value+': '+textvalue+intText+'</span><span><img src=cancel.png onclick=removeQuestOjbective(this) class=Hand></span></div>';
      f.QuestObjType.value = 'Talk to NPC';
      f.QuestObjUseText.value = '';
      f.QuestObjUseNumber.value = '1';
      f.QuestObjUseID.value = '';
      f.QuestImageSrc.value = '';
      f.QuestImageId.value = '';
      
      f.QuestCollectItemType.value = '';
      $('QuestGetItemTextSpan').innerHTML = '';
      displayNone($('QuestGetItemTextSpan'));
      f.QuestGetItemID.value = '';
      f.QuestGetItemText.value = 'Search...';
      f.QuestGetItemText.style.fontStyle = 'italic';
      displayInline(f.QuestGetItemText);
      
      $('QuestGetItemLocTextSpan').innerHTML = '';
      displayNone($('QuestGetItemLocTextSpan'));
      f.QuestGetItemLocID.value = '';
      f.QuestGetItemLocText.value = 'Search...';
      f.QuestGetItemLocText.style.fontStyle = 'italic';
      displayInline(f.QuestGetItemLocText);
      
      displayNone($('collectItemDiv'));
      
      displayNone($('QuestObjUseTextSpan'));
      $('QuestObjUseTextSpan').innerHTML = '';
      displayInline(f.QuestObjUseText);
      app.questObjectiveCount++;
}

function addQuestStep(force) {
   if (app.questObjectiveCount == 0) return false;
   var update = app.questStepUpdate;   
   if (typeof app.questStepCount == 'undefined') app.questStepCount = 0;
      var f = document.forms.Quest;
      var list = $('QuestStepList');
      var s = (app.questObjectiveCount > 1) ? 's' : '';
      var title = f['QuestStepTitle'].value.replace(/[|:;]/g,'');
      if (title == '') {
         if (app.questStepCount == 0) {
            title = 'Start';
         } else {
            title = 'Step '+(app.questStepCount);
         }
      }
         
      var descvalue = f['QuestStepDescript'].value.replace(/[|:;]/g,'');
      var dialog = f['QuestStepDialog'].value.replace(/[|:;]/g,'');
      var stepToEdit = (update || force) ? app.questStepToEdit : app.questStepCount;
      var idValue = (update || force) ? app.questStepToEdit : 0;
      var html = '<span class=dNone>'+title+'</span>'
      +'<span class=dNone>'+descvalue+'</span><span class=dNone>'+dialog+'</span>'
      +'<span class=dNone>'+($('QuestObjectiveList').innerHTML)+'</span>'
      +'<span class=dNone>'+idValue+'</span>'
      +'<span><a href="javascript:selectQuestStep('+stepToEdit+')">'+title+'</a></span><span><img src=cancel.png onclick=removeQuestStep(this) class=Hand></span></div>';

      if (update) {
         $('qs'+app.questStepToEdit).innerHTML = html;
      } else if (force) {
         list.innerHTML += '<div id="qs'+app.questStepToEdit+'">'+html+'</div>';
      } else {
         list.innerHTML += '<div id="qs'+app.questStepCount+'">'+html+'</div>';
      }

   app.questObjectiveCount = 0;
   $('QuestObjectiveList').innerHTML = '';
      f.QuestObjType.value = 'Talk to NPC';
      f.QuestObjUseText.value = '';
      f.QuestObjUseNumber.value = '1';
      f.QuestObjUseID.value = '';
      f.QuestImageSrc.value = '';
      f.QuestImageId.value = '';  
      f['QuestStepTitle'].value = '';
   
      f.QuestCollectItemType.value = '';
      $('QuestGetItemTextSpan').innerHTML = '';
      displayNone($('QuestGetItemTextSpan'));
      f.QuestGetItemID.value = '';
      f.QuestGetItemText.value = 'Search...';
      f.QuestGetItemText.style.fontStyle = 'italic';
      displayInline(f.QuestGetItemText);
      
      $('QuestGetItemLocTextSpan').innerHTML = '';
      displayNone($('QuestGetItemLocTextSpan'));
      f.QuestGetItemLocID.value = '';
      f.QuestGetItemLocText.value = 'Search...';
      f.QuestGetItemLocText.style.fontStyle = 'italic';
      displayInline(f.QuestGetItemLocText);;   
   
   f.QuestStepDescript.value = '';
   f['QuestStepDialog'].value = '';
   
   if (update) {
      questStepCancel();
   } else {
      app.questStepCount++;
   }
}

function selectQuestStep(id) {
   var step = $('qs'+id);
   var f = document.forms.Quest;
      
   f['QuestStepTitle'].value = step.childNodes[0].innerHTML;
   f.QuestStepDescript.value = step.childNodes[1].innerHTML;
   f['QuestStepDialog'].value = step.childNodes[2].innerHTML;
   f.QuestStepID.value = step.childNodes[4].innerHTML;
   $('QuestObjectiveList').innerHTML = '';
   var oList = step.childNodes[3];
   for (var i = 0; i < oList.childNodes.length; i++) {
      //type:text:int:idvalue
      //images
      
      var arry = oList.childNodes[i].firstChild.innerHTML.split(':');
      f.QuestObjType.value = arry[0];
      f.QuestObjUseText.value = arry[1];
      $('QuestObjUseTextSpan').innerHTML = '<span><span>'+arry[1]+'</span></span>';
      f.QuestObjUseNumber.value = arry[2];
      f.QuestObjUseID.value = arry[3];
      arry = oList.childNodes[i].childNodes[1].innerHTML.split(':');
      f.QuestImageSrc.value = arry[0];
      f.QuestImageId.value = arry[1]; 
            if (f.QuestObjType.value == 'Collect Item') {
               //itemType:itemName:itemID:itemLocName:itemLocID
               arry = oList.childNodes[i].childNodes[2].innerHTML.split(':');
               f.QuestCollectItemType.value = arry[0];
               f.QuestGetItemID.value = arry[2];
               $('QuestGetItemTextSpan').innerHTML = '<span>'+arry[1]+'</span>';

               f.QuestGetItemLocID.value = arry[4];
               $('QuestGetItemLocTextSpan').innerHTML = '<span>'+arry[3]+'</span>';

            }

       
      addQuestObjective();
   }
   
   app.questStepToEdit = id;
   app.questStepUpdate = true;
   displayInline(f.questStepCancelButton);
   f.QuestStepButton.value = "Update Objective(s) in Step";
}

function questStepCancel() {
   var f = document.forms.Quest;
   app.questStepToEdit = 0;
   app.questStepUpdate = false;
   displayNone(f.questStepCancelButton);
   f.QuestStepButton.value = "Add Objective(s) as a Step";
}


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

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

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

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

function addQuestReward(f) {
   var v = f.QuestReward.value.replace(/[|:]/g,'');
   if (v == '') return false;
   var n = f.QuestRewardCount.value.replace(/[^0-9]/g,'');
   if (n == '') return false;
   var list = $('QuestRewardList');
   var selectable = f.QuestSelectable.checked;
   list.innerHTML += '<div><span>'+n+':'+v+':'+selectable+'</span><span><img src=cancel.png onclick=removeQuestReward(this) class=Hand></span></div>';
   f.QuestRewardCount.value = '1';
   f.QuestReward.value = '';
}
function addQuestRelated(f) {
   var t = f.QuestRelatedType.value;
   if (t == '') return false;
   var v = f.QuestRelatedText.value.replace(/[|:]/g,'');
   if (v == '') return false;
   var comment = f.QuestRelatedComment.value.replace(/[|:]/g,'');
   var list = $('QuestRelatedList');
   list.innerHTML += '<div><span>'+t+':'+v+':'+comment+'</span><span><img src=cancel.png onclick=removeQuestRelated(this) class=Hand></span></div>';
   f.QuestRelatedText.value = '';
   f.QuestRelatedComment.value = '';
}

function checkQuestStepType(s) {
   if (s.value == 'Collect Item') {
      displayBlock($('collectItemDiv'));
   } else {
      displayNone($('collectItemDiv'));
   }
}

function questSelectItem() {
   var f = document.forms.Quest;
   if (app.autoSuggest.col2ID != 0) {
      $('QuestGetItemLocTextSpan').idField  =  f.QuestGetItemLocID;
      $('QuestGetItemLocTextSpan').textField = f.QuestGetItemLocText;       
      $('QuestGetItemLocTextSpan').innerHTML = '<span>'+app.autoSuggest.col2Value+'</span><img src=cancel.png class=Hand onclick=cancelLocation(this) style=\'padding-left: 3\'>';
      f.QuestGetItemLocID.value = app.autoSuggest.col2ID;
      displayNone(f.QuestGetItemLocText);
      displayInline($('QuestGetItemLocTextSpan'));
   }

}