/******************************************************************************
 *
 *  Copyright 2008 David D. Emory [additional contributors append names here]
 *
 *  This file is part of Five Points. See <http://www.fpdev.org> for
 *  additional project information and documentation.
 *  
 *  Five Points is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  Five Points is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 *  
 ******************************************************************************/  

function fp_trpErrorMsg(title, msg) {
  var html = "";
  html = html + "<div style='background:url(img/icons/xicon.gif); background-repeat:no-repeat; padding-left:40px;'>";
  html = html + "<b>"+title+"</b>";
  html = html + "<p>"+msg;
  html = html + "</div>";
	
  return html;
}


//function fp_tMakeResolveRequest() {
//  createProcessingMsg("Resolving Start/End Locations...");
//
//  var http_request = false;
//
//  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
//    http_request = new XMLHttpRequest();
//    if (http_request.overrideMimeType) {
//      http_request.overrideMimeType('text/xml');
//    }
//  } else if (window.ActiveXObject) { // IE
//    try {
//      http_request = new ActiveXObject("Msxml2.XMLHTTP");
//    } catch (e) {
//      try {
//        http_request = new ActiveXObject("Microsoft.XMLHTTP");
//      } catch (e) {}
//    }
//  }
//
//  if (!http_request) {
//    alert('Giving up :( Cannot create an XMLHTTP instance');
//    return false;
//  }
//
//  // initialize fields
//  var startInput = document.getElementById("startLocInput");
//  var endInput = document.getElementById("endLocInput");
//  var fields = "start="+escape(startInput.value)+"&end="+escape(endInput.value);
//
//  http_request.onreadystatechange = function() {
//    fp_alertResolveContents(http_request);
//  };
//  http_request.open('POST', 'trip1_resolve.php', true);
//  http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//  http_request.send(fields);
//
//}



//function fp_alertResolveContents(http_request) {
//  if (http_request.readyState == 4) {
//    if (http_request.status == 200) {
//      //alert("aRC");
//      var xmlDoc = http_request.responseXML;
//      var topNode = xmlDoc.documentElement;
//      for (var iNode = 0; iNode < topNode.childNodes.length; iNode++) {
//        var node = topNode.childNodes.item(iNode);
//        //alert("ch name: "+node.nodeName);//node.attributes.getNamedItem("disp"));
//        if(node.nodeName == "startlocs") processStartLocsXML(node, true);
//        if(node.nodeName == "endlocs") processEndLocsXML(node, true);
//      }
//      if(startLocCount_ == 1 && endLocCount_ == 1) {
//        makeTripRequest();
//      }
//      else {
//        var output = document.getElementById("outputArea");
//        var html = "";
//        if(startLocCount_ >= 1 && endLocCount_ >= 1) {
//          html += "<div class='generalMsg'>";
//          html += "<div class='genMsgHeader'>";
//          html += "<table border=0 align=center><tr>";
//          html += "<td width=40 align='left'><img src='images/trip/qmicon.gif' style='display:block;'></td>";
//          html += "<td height=32>Clarification is Needed for Your Location Input</td>";
//          html += "</tr></table>";
//          html += "</div>";
//          if(startLocCount_ > 1 && endLocCount_ == 1) html += "Your start location resolves ";
//          else if(startLocCount_ == 1 && endLocCount_ > 1) html += "Your end location resolves ";
//          else if(startLocCount_ > 1 && endLocCount_ > 1) html += "Both your start and end locations resolve ";
//          html += "to multiple places in the A-TRAIN database. Please review the list";
//          html +=(startLocCount_ > 1 && endLocCount_ > 1 ? "s" : "");
//          html += " of possible resolutions and select the appropriate item";
//          html +=(startLocCount_ > 1 && endLocCount_ > 1 ? "s." : ".");
//          html += "</div>";
//        }
//        else {
//          var msg = "Your ";
//          if(startLocCount_ == 0) msg += "start";
//          if(endLocCount_ == 0 && startLocCount_ == 0) msg += " and ";
//          if(endLocCount_ == 0) msg += "end";
//          msg += " location" + (endLocCount_ == 0 && startLocCount_ == 0 ? "s" : "");
//          msg += " could not be successfully resolved.<br />&nbsp;<br />"
//          msg += generateTip("If the application is not recognizing a valid address, there may be an error in the street network data. Try specifying the nearest intersection as an alternative.");
//          html = generateErrorMsg("Could Not Resolve Location Input", msg);
//        }
//        output.innerHTML = html;
//
//        // expand entry boxes:
//        //alert(startLocCount_ + " " + endLocCount_);
//        if(startLocCount_ > 1) expandStartBox();
//        if(endLocCount_ > 1) expandEndBox();
//
//
//      }
//    } else {
//      alert('There was a problem with the request.');
//    }
//  }
//}

function fp_makeTripRequest(scenID) {
  if(scenID == 1) {
    fp_oTabSelected(FP_OUTPUT_RESULTS);
    fp_trpProcessingMsg("Computing your Itinerary...");
  }

  //newTimeInput();
  tripType_ = fp_eGetTripType();
  var timeInput = document.getElementById("fp_timeInput").value;
  var hour = fp_eGetHoursFromInput(timeInput);
  var minute = fp_eGetMinutesFromInput(timeInput);
  var ampm = fp_eGetAMPMFromInput(timeInput);
  var day = document.getElementById("fp_dayInput").value;
  var deparr = document.getElementById("fp_depArrInput").value;
  var optmode = "na";
  var nmspeed = document.getElementById("fp_eSpeed").value;
  var nmradius = document.getElementById("fp_eRadius").value;
  var typefact = fp_teBTFacPct_;
  var topfact = fp_teBTTopoPct_;

  //alert("topFact="+fp_ebTPct_+", typeFact="+fp_ebFPct_);
  var fields = "triptype="+tripType_+"&start="+escape(fp_encodedStartLoc_)+"&end="+escape(fp_encodedEndLoc_)+"&hour="+escape(hour)+"&min="+escape(minute)+"&ampm="+escape(ampm)+"&day="+escape(day)+"&deparr="+escape(deparr)+"&optmode="+escape(optmode)+"&nmspeed="+escape(nmspeed)+"&nmradius="+escape(nmradius)+"&typefact="+escape(typefact)+"&topfact="+escape(topfact)+"&scenid="+escape(scenID);
	
  //prompt("fields:", fields);

  fp_ajaxLoadAsXML("fp_trpact_plantrip.php", scenID == 1 ? fp_alertTripResponse : fp_alertSpecialTripResponse, fields)
}


function fp_alertTripResponse(xmlDoc) {
   var output = fp_outputDivs_[FP_OUTPUT_RESULTS];
   while (output.firstChild) output.removeChild(output.firstChild);
   
   var foundTripTT = false, foundTripNT = false, foundTripNM = false;
   var msgHtml = "The following messages were returned by the server:";
   var topNode = xmlDoc.documentElement;
   
   if(topNode.nodeName == "plantrip") {
     fp_tServerName_ = topNode.getAttribute("server");
     fp_tQueryTime_ = topNode.getAttribute("qtime");
     fp_tQueryLength_ = topNode.getAttribute("qlensec");
   }
   
   // count/initialize walk groups
   var walkGrpCount = 0;
   for (var i = 0; i < topNode.childNodes.length; i++) {
     var node = topNode.childNodes.item(i);
     if(node.nodeName == "trip") {
       for (var ti = 0; ti < node.childNodes.length; ti++) {
         var tiNode = node.childNodes.item(ti);
         if(tiNode.nodeName == "walk" || tiNode.nodeName == "bike") walkGrpCount++;
       }
     }
   }
   fp_ptInitWalkInfo(walkGrpCount);
   
   
   for (var i = 0; i < topNode.childNodes.length; i++) {
     var node = topNode.childNodes.item(i);
     if(node.nodeName == "trip" && node.getAttribute("type") == "tt") { // travel time trip
       fp_tMapIdTT_ = node.getAttribute("listid");
       fp_initPT("tt");
       fp_tmapbxtt_ = node.getAttribute("bx");
       fp_tmapbytt_ = node.getAttribute("by");
       fp_tmapbwtt_ = node.getAttribute("bw");
       fp_tmapbhtt_ = node.getAttribute("bh");
   
       fp_processTrip(node);
       foundTripTT = true;
     }
     if(node.nodeName == "trip" && node.getAttribute("type") == "nt") { // number of transfers trip
       fp_tMapIdNT_ = node.getAttribute("listid");
       fp_initPT("nt");
       fp_tmapbxnt_ = node.getAttribute("bx");
       fp_tmapbynt_ = node.getAttribute("by");
       fp_tmapbwnt_ = node.getAttribute("bw");
       fp_tmapbhnt_ = node.getAttribute("bh");
       fp_processTrip(node);
       foundTripNT = true;
     }
     if(node.nodeName == "trip" && node.getAttribute("type") == "nm") { // non-motorized trip
       fp_tMapIdNM_ = node.getAttribute("listid");
       fp_initPT("nm");
       fp_processTrip(node);
       foundTripNM = true;
     }
     else if(node.nodeName == "msg") msgHtml += "<p><i>"+node.childNodes[0].nodeValue+"</i></p>";
   }
   
   
   if(!foundTripTT && !foundTripNT && !foundTripNM) { // no trip found
     fp_tTripTimeTT_ = 0;
     var noTripDiv = document.createElement("div");
     noTripDiv.id="fp_tNoTripFoundMsg";
     noTripDiv.innerHTML = fp_trpErrorMsg("No Trip Found", msgHtml);
     output.appendChild(noTripDiv);

     // start special search
     /*var specialResultsRowDiv = document.createElement("div");
     specialResultsRowDiv.id="fp_tSpecialResultsRow";
     specialResultsRowDiv.style.marginBottom = "10px";
     specialResultsRowDiv.style.padding = "3px";
     specialResultsRowDiv.style.background = "#FFA07A";
     output.appendChild(specialResultsRowDiv);
     specialResultsRowDiv.innerHTML = "Performing your search on Concept 3...";
     fp_makeTripRequest(3);*/
   }
   else { // trip found
     
     fp_tPrepareResultsOutput();
     
     if(fp_eSelectedTab_==2) { // bike-only trip
       fp_createTopoGraph();
       //var tgDiv = document.getElementById("fp_topoGraph");
       fp_topoDiv_.innerHTML = "<img src='fp_trpact_topograph.php?id="+fp_tMapIdNM_+"'>";
     }
     else fp_removeTopoGraph();
     
     if(foundTripNM) fp_tShowNonMotorizedTrip();
     else {
       //document.getElementById("ttTabInfo").innerHTML = tripTimeTT_+" &bull; "+(numTransfersTT_ <= 0 ? "No" : numTransfersTT_)+" transfer"+(numTransfersTT_==1 ? "" : "s");
       //document.getElementById("ntTabInfo").innerHTML = tripTimeNT_+" &bull; "+(numTransfersNT_ <= 0 ? "No" : numTransfersNT_)+" transfer"+(numTransfersNT_==1 ? "" : "s");
       fp_tShowTravelTimeTrip();
     }
   }
}

function fp_alertSpecialTripResponse(xmlDoc) {
   //var output = fp_outputDivs_[FP_OUTPUT_RESULTS];
   //while (output.firstChild) output.removeChild(output.firstChild);

   var foundTripTT = false;//, foundTripNT = false, foundTripNM = false;
   var msgHtml = "The following messages were returned by the server:";
   var topNode = xmlDoc.documentElement;

//   if(topNode.nodeName == "plantrip") {
//     fp_tServerName_ = topNode.getAttribute("server");
//     fp_tQueryTime_ = topNode.getAttribute("qtime");
//     fp_tQueryLength_ = topNode.getAttribute("qlensec");
//   }

   // count/initialize walk groups
   var walkGrpCount = 0;
   for (var i = 0; i < topNode.childNodes.length; i++) {
     var node = topNode.childNodes.item(i);
     if(node.nodeName == "trip") {
       for (var ti = 0; ti < node.childNodes.length; ti++) {
         var tiNode = node.childNodes.item(ti);
         if(tiNode.nodeName == "walk" || tiNode.nodeName == "bike") walkGrpCount++;
       }
     }
   }
   fp_ptInitWalkInfo(walkGrpCount);


   for (var i = 0; i < topNode.childNodes.length; i++) {
     var node = topNode.childNodes.item(i);
     if(node.nodeName == "trip" && node.getAttribute("type") == "tt") { // travel time trip
       fp_tMapIdSP_ = node.getAttribute("listid");
       fp_initPT("sp");
       fp_tmapbxsp_ = node.getAttribute("bx");
       fp_tmapbysp_ = node.getAttribute("by");
       fp_tmapbwsp_ = node.getAttribute("bw");
       fp_tmapbhsp_ = node.getAttribute("bh");

       fp_processTrip(node);
       foundTripTT = true;
     }
     else if(node.nodeName == "msg") msgHtml += "<p><i>"+node.childNodes[0].nodeValue+"</i></p>";
   }


   if(foundTripTT) {
     //fp_tPrepareResultsOutput();
     fp_removeTopoGraph();
     if(fp_tTripTimeTT_ == 0) {
       
       fp_tPrepareResultsOutput();
       var spResultsRowDiv = document.getElementById("fp_tSpecialResultsRow");
       spResultsRowDiv.innerHTML = "<img src='http://fp.atltransit.com/images/trip/vwcta.gif' align='left' style='margin-right:3px;'>This trip would be possible on transit if <a href=''>Concept 3</a> were built. [<a href='javascript:fp_showSpecialTrip(false)'><b>Show Trip</b></a>]";
     }
     else {
       var spResultsRowDiv = document.getElementById("fp_tSpecialResultsRow");
       spResultsRowDiv.innerHTML = "<img src='http://fp.atltransit.com/images/trip/vwcta.gif' align='left' style='margin-right:3px;'>This trip could be shortened by <b>"+fp_elapsedTimeStr(fp_tTripTimeTT_-fp_tTripTimeSP_)+"</b> if <a href=''>Concept 3</a> were built. [<a href='javascript:fp_showSpecialTrip(true)'><b>Show Trip</b></a>]";
     }
   }
}

