// Functions specific to the STATIONS locator.
// For a NEWLOCATOR, create a new version of this file. 
// All of the functions in this file must be present in new
// locators, even if they don't do anything.

var apptype = "stations";

// Perform any required processing prior to invoking the ajax call.
function appPreSubmit() {

}

/**
 * return a div element for the printable results table
 */
function getPrintableResults(location, index) {
   var resultDiv = document.createElement('div');
   // split the payment_type into two lines
   var paymentType = "";
   if (location['PAYMENT_TYPE']) {
      var words = location['PAYMENT_TYPE'].split(' ');
      for (var i = 0; i < words.length; i++) {
         paymentType += words[i] + " ";
         if (i%2 == 0 && i < words.length-1) {
            paymentType += "<br>";
         }
      }
   }

   var result_html = "<b>" + location['STATION_NAME'] + "</b><br>" +
      location['FUEL_TYPE_CODE'] + "<br>" +
      location['STREET_ADDRESS'] + "<br>" +
      location['CITY'] + ", " +
      location['ST_PRV_CODE'] + " " +
      location['ZIP'] + "<br>";

   if(location["STATION_PHONE"]) {
      result_html += "<b>Phone:</b> " + location['STATION_PHONE'] + "<br>";
   }

   if(location["DISTANCE"] != undefined) {
      result_html += "<b>Distance</b>: " + roundNumber(location['DISTANCE'], 1) + " Miles" + "<br>";
   }

   if(location["DIRECTIONS"]) {
      result_html += "<b>Intersection Directions:</b> " + location['DIRECTIONS'] + "<br>";
   }

   if(paymentType) {
      result_html += "<b>Payment:</b> " + paymentType + "<br>";
   }

   result_html += "<b>Access:</b> " + location['GROUPS_WITH_ACCESS_CODE'];

   resultDiv.innerHTML = result_html;
   return resultDiv;
}


// Add a marker to the map
// index specifies which icon to use (A, B, C, etc).
function addMarker(location, index) {
   var icon = G_DEFAULT_ICON;
   if(useLetteredMarkers()) {
      icon = get_Lettered_Icon(location['FUEL_TYPE_CODE'],index);
   }
   else
   {
      icon = get_Lettered_Icon(location['FUEL_TYPE_CODE'])
   }

   var marker = new GMarker(new GLatLng(location['LATITUDE'], location['LONGITUDE']), icon);
   GEvent.addListener(marker, 'click',
                function() {
                        marker.openInfoWindowHtml(getDescription(location), {
                           maxWidth: 350
                        });
                }
        );
        map.addOverlay(marker);
   markers[index] = marker;
}


// return a div element for the entry in the result list for a given station
// May be overridden in apptype.js
function getResultListContent(location, index) {
   var url = "";
   if(useLetteredMarkers()) {
      url = fig_pic(location['FUEL_TYPE_CODE'],index); // otherwise get an icon based on the current index
   } else {
      url = fig_pic(location['FUEL_TYPE_CODE'],-2);
   }
   var resultDiv = document.createElement('div');
  // Define a function to re-center the map and open the popup bubble when the user
  // clicks on the location name.
   var focus = function() {
      markers[index].openInfoWindowHtml(getDescription(location), {
         maxWidth: 350
      });
      map.panTo(new GLatLng(location['LATITUDE'], location['LONGITUDE']));
      return false;
   }
   titleLink = document.createElement('a');
   titleLink.href = "#";
   titleLink.onclick = focus;
   //titleLink.appendChild(document.createElement('<span class=\"station_name\">'));
   titleLink.appendChild(document.createTextNode(location['STATION_NAME']));
   iconImg = document.createElement('img');
   iconImg.src = url;
   //alert(url);

   var iconDiv = document.createElement("div");
   iconDiv.className = "result_icon";
   iconDiv.appendChild(iconImg);

   var detailsDiv = document.createElement("div");
   detailsDiv.className = "result_details";
   detailsDiv.appendChild(titleLink);
   detailsDiv.appendChild(document.createElement('br'));
   if(location["FUEL_TYPE_CODE"]) {
      detailsDiv.appendChild(document.createTextNode(location['FUEL_TYPE_CODE']));
      detailsDiv.appendChild(document.createElement('br'));
   }

   if(location["STREET_ADDRESS"]) {
      detailsDiv.appendChild(document.createTextNode(location['STREET_ADDRESS']));
      detailsDiv.appendChild(document.createElement('br'));
   }

   if(location["CITY"]) {
      detailsDiv.appendChild(document.createTextNode(location['CITY'] + " "));
   }

   if(location["ST_PRV_CODE"]) {
      detailsDiv.appendChild(document.createTextNode(location['ST_PRV_CODE'] + " "));
   }

   if(location["ZIP"]) {
      detailsDiv.appendChild(document.createTextNode(location['ZIP']));
   }

   detailsDiv.appendChild(document.createElement('br'));

   if(location["BD_BLENDS"]) {
      detailsDiv.appendChild(document.createTextNode("Biodiesel Blends: " + location['BD_BLENDS']));
      detailsDiv.appendChild(document.createElement('br'));
   }

   if(location['STATION_PHONE']) {
      detailsDiv.appendChild(document.createTextNode("Phone: " + location['STATION_PHONE']));
      detailsDiv.appendChild(document.createElement('br'));
   }

   if (!showAll) {
      var round_dist=roundNumber(location['DISTANCE'],1);
      detailsDiv.appendChild(document.createTextNode("Distance: " + round_dist + " Miles"));
      detailsDiv.appendChild(document.createElement('br'));
   }
   detailsDiv.appendChild(document.createTextNode("Access: " + location['GROUPS_WITH_ACCESS_CODE']));
   detailsDiv.appendChild(document.createElement('br'));

   var resultDiv = document.createElement('div');
   resultDiv.className = "result_item";
   resultDiv.appendChild(iconDiv);
   resultDiv.appendChild(detailsDiv);

   return resultDiv;
}



// Get an icon using google's lettered icons
// Input parameter can be a letter (the returned Icon is uses the provided letter (limited to A-J))
// or a number, in which case 0->A, 1->B, etc.
// Returns a GIcon object
function get_Lettered_Icon(fuel,index) {

   // We have a URL to the icon, now create and return a GIcon object
   var icon = new GIcon();

  if (index || index == 0)
   {
   //alert(index);
   var URL = fig_pic(fuel,index);
   icon.iconSize = new GSize(24,34);
   icon.iconAnchor = new GPoint(0,34);
   }
   else
   {
   var URL = fig_pic_without(fuel);
   icon.iconSize = new GSize(10,14);
   icon.iconAnchor = new GPoint(0,15);
   }

   icon.infoWindowAnchor = new GPoint(9,2);
   icon.image = URL;
   return icon;
}

function fig_pic(fuel,count)
{
    var pic_fuel, num_part, pic, tcount;

tcount=count;

if (count >= 10 ) 
  {
  count=count%10;
  }

if (fuel == "Biodiesel (B20 and above)" )
 {
  pic_fuel="biodiesel_";
 }
else if (fuel == "Compressed Natural Gas" )
 {
  pic_fuel="cng_";
 }
else if (fuel == "Liquefied Natural Gas (LNG)" )
 {
  pic_fuel="lng_";
 }
else if (fuel == "Ethanol (E85)" )
 {
  pic_fuel="ethanol_";
 }
else if (fuel == "Electric" )
 {
  pic_fuel="electric_";
 }
else if (fuel == "Hydrogen" )
 {
  pic_fuel="hydrogen_";
 }
else if (fuel == "Liquefied Petroleum Gas (Propane)" )
 {
  pic_fuel="propane_";
 }
else
 {
  pic_fuel="not found";
 }

if (tcount == -2 )
 {
 num_part="nn.png";
 }
else if (count == 0 )
 {
 num_part="a.png";
 }
else if (count == 1 )
 {
 num_part="b.png";
 }
else if (count == 2 )
 {
 num_part="c.png";
 }
else if (count == 3 )
 {
 num_part="d.png";
 }
else if (count == 4 )
 {
 num_part="e.png";
 }
else if (count == 5 )
 {
 num_part="f.png";
 }
else if (count == 6 )
 {
 num_part="g.png";
 }
else if (count == 7 )
 {
 num_part="h.png";
 }
else if (count == 8 )
 {
 num_part="i.png";
 }
else if (count == 9 )
 {
 num_part="j.png";
 }
else 
 {
 num_part="a.png";
 }

pic= baseHref + "images/loc_icons/" + pic_fuel + num_part;

return(pic);

}



function fig_pic_without(fuel)
{
    var pic_fuel, pic;

if (fuel == "Biodiesel (B20 and above)" )
 {
  pic_fuel="biodiesel_tiny.png";
 }
else if (fuel == "Compressed Natural Gas" )
 {
  pic_fuel="cng_tiny.png";
 }
else if (fuel == "Liquefied Natural Gas (LNG)" )
 {
  pic_fuel="lng_tiny.png";
 }
else if (fuel == "Ethanol (E85)" )
 {
  pic_fuel="ethanol_tiny.png";
 }
else if (fuel == "Electric" )
 {
  pic_fuel="electric_tiny.png";
 }
else if (fuel == "Hydrogen" )
 {
  pic_fuel="hydrogen_tiny.png";
 }
else if (fuel == "Liquefied Petroleum Gas (Propane)" )
 {
  pic_fuel="propane_tiny.png";
 }
else
 {
  pic_fuel="not found";
 }


pic="images/loc_icons/" + pic_fuel; 

return(pic);


}

/**
 * Returns the URL of the icon for a given location at a certain index. The
 * icon's shape and color will vary depending on the station's fuel type.
 */
function getLocationIconUrl(location, index) {
   var url;
   if(index == null) {
      url = fig_pic_without(location["FUEL_TYPE_CODE"]);
   } else {
      url = fig_pic(location["FUEL_TYPE_CODE"], index);
   }

   return url;
}


function fig_fuels()
 {
  // check to see if at least one fuel is checked
 flength=document.getElementsByName('fuels[]').length;
 //alert(flength);
 fuel_count=0;
 fuel_str="";
      for (var i = 0; i < flength; i++)
       {
       if ( document.getElementsByName('fuels[]')[i].checked)
         {
          var tval=document.getElementsByName('fuels[]')[i].value;
          fuel_count++;
          fuel_str = fuel_str + tval + "|";
          //alert(tval);
         }
       }
      //alert(fuel_str);
      if ( fuel_count==0 || tval == 'zipo' )
        {
        alert_str="Please Enter One or More Fuels from the Pick List";
        alert(alert_str);
        return(false);
        }

 stationsPreSubmit();

 }





function turn_on(it)
{
  document.getElementById(it).style.display = "";
  tval="Shoud be visible";
  //alert(tval);
}


function turn_off(it)
{
  document.getElementById(it).style.display = "none";
  tval="Shoud be hidden";
  //alert(tval);
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}




// Stations pre-submit function - executes code prior to submitting the form, then calls
// the application specific pre-submit
// this is the exact same program as common pre-submit but this functions calls validateStations

function stationsPreSubmit() {
   // Perform application specific processing prior to form submission
   appPreSubmit();
   
   // Perform client side input validation
   if (!validateStations()) {
      return;
   } 
   
   // If this is a state-based search, set a flag to cause all of the
   // results to be shown on a single map rather than paging them. 
   var state_sel = document.getElementById('state_select');
   var start_addr = document.getElementById('start_address');
   var end_addr = document.getElementById('end_address');
   var addr_input = document.getElementById('address_input');
   
   // The third check in the if statement below determines whether
   // the user typed only a state into the address box. In that case, we treat
   // the query like a state query. sjaxGetRequest makes a synchronous
   // call to the server
   if (document.getElementById("form_type_state").checked ||
       document.getElementById("form_type_route").checked) {
      showAll = true;
   } else {
      showAll = false;

      if(sjaxGetRequest("includes/isState.php?value=" + addr_input.value) != "") {
         basicStateSearch = true;
      }
   }
   // For the advanced search, make sure that only values in the currently visible
   // search mode are filled out. For example, if the user selects a state, then
   // switches to address and submits the form, we want to clear the state selection
   if (document.getElementById('form_type_address').checked) {
      if (state_sel != undefined)
         state_sel.value = "";
      if (start_addr != undefined)
         start_addr.value = "";
      if (end_addr != undefined)
         end_addr.value = "";
   }
   
   if (document.getElementById('form_type_state').checked) {
      if (addr_input != undefined) addr_input.value = "";
      if (start_addr != undefined) start_addr.value = "";
      if (end_addr != undefined) end_addr.value = "";
   }
   
   if (document.getElementById('form_type_route').checked) {
      if (addr_input != undefined) addr_input.value = "";
      if (state_sel != undefined) state_sel.value = "";
   }
   
   // Clear previous search results
   document.getElementById('result_list').innerHTML = "";
   map.clearOverlays();
   
   // Show the modal loading dialog
   document.getElementById('loading').style.visibility="visible";
   
   // If this is a route based search,
   // Get the route from google here, plot it on the map,
   // then create a json string containing the route waypoints and send it
   // to getStations.php. We can still handle the results with the common
   // handleResults.
   if (document.getElementById("form_type_route").checked) { 
      directions = new GDirections(map, document.getElementById('result_list'));
      startLocation = document.getElementById('start_address').value;
      endLocation = document.getElementById('end_address').value;
   
      directions.load("from: " + startLocation + " to: " + endLocation);
   
      GEvent.addListener(directions, "load", function() {
         // Listener invoked once directions results are available.
         // Now we can make our ajax call.
         
         // First get a list of vertices from the directions object
         // Google returns too many vertices for the SDO_GEOMETRY function. (vertexScaling)
         polyline = directions.getPolyline();
         vertexArray = new Array();
         vertexNumber = 0;
         vertexScaling = Math.round(polyline.getVertexCount() / 50);
         for (i = 0; i < polyline.getVertexCount(); i++) {
            point = new Object();
            point.lat= polyline.getVertex(i).lat();
            point.lon= polyline.getVertex(i).lng();
            if (i % vertexScaling == 0) { 
               vertexArray[vertexNumber++] = point;
            }
         }
         // Send the vertices to the server to get the station list
         currentSearchParams = "vertices=" + JSON.stringify(vertexArray)
                         + "&" + encodePostParams(document.getElementById('locatorform'));
         ajaxPostRequest('/afdc/locator/getStations.php', currentSearchParams, handleSearchResults);
      
      });
   
      // Add an error event listener to the GDirections object
      GEvent.addListener(directions, "error", function() {
         alert("Unable to locate one or both of the addresses provided (Geocode Status: "
               + directions.getStatus().code + ")");
         document.getElementById('loading').style.visibility="hidden";
      });
   } else {
      // Else send a normal (non-route) ajax request
      currentSearchParams = encodePostParams(document.getElementById('locatorform'));
      ajaxPostRequest('/afdc/locator/getStations.php', currentSearchParams, handleSearchResults);   
   }
   
}


/**
 * Perform client side input validation on form fields
 */
function validateStations() {
   var state_sel = (document.getElementById('state_select') == undefined) ? "" : document.getElementById('state_select').value;
   var start_addr = (document.getElementById('start_address') == undefined) ? "" : document.getElementById('start_address').value;
   var end_addr = (document.getElementById('end_address') == undefined) ? "" : document.getElementById('end_address').value;
   var addr_input = (document.getElementById('address_input') == undefined) ? "" : document.getElementById('address_input').value;
   var route_radius = (document.getElementById('route_mile') == undefined) ? "" : document.getElementById('route_mile').value;
   var addr_radius = (document.getElementById('mile') == undefined) ? "" : document.getElementById('mile').value;

   if (document.getElementById('form_type_address').checked) {
      if (addr_input == "") {
         alert("Please enter a valid address");
         return false;
      }

      if (addr_radius == "" || addr_radius < 0.1 || addr_radius > 500) {
         alert("Please enter a search radius between 0.1 and 500 miles");
         return false;
      }
   }
   
   if (document.getElementById('form_type_state').checked) {
      if (state_sel == "") {
         alert("Please Select a State");
         return false;
      }
   }
   
   if (document.getElementById('form_type_route').checked) {
      if (start_addr == "") {
         alert("Please enter a starting address for your route");
         return false;
      }
      if (end_addr == "") {
         alert("Please enter an ending address for your route");
         return false;
      }
      if (route_radius == "" || route_radius < 0.1 || route_radius > 50) {
         alert("Please enter a search radius between 0.1 and 50 miles");
         return false;
      }
   }
   return true;
}

