// 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(onload) {
   if(!fig_fuels(onload)) {
      return false;
   }

   return true;
}

// Turn on or off the electrical station types
function elec_types(checkbox) {
	if (checkbox.checked == true) document.getElementById("electric_types").style.display="block";
	else document.getElementById("electric_types").style.display="none";
}

/**
 * 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) {
//alert(location['DC_FAST_NUM']);
   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["FUEL_TYPE_CODE"] == "Electric") {
      var typestr = '';
      if (location["LEVEL1_EVSE_NUM"]) typestr += 'Level 1';
      if (location["LEVEL2_EVSE_NUM"]) {
   		if (typestr != '') typestr += ', ';
   		typestr += 'Level 2';
   	  }
      if (location["DC_FAST_NUM"]) {
   		if (typestr != '') typestr += ', ';
   		typestr += 'DC Fast';
   	  }
      if (location["OTHER_EVSE"]) {
   		if (typestr != '') typestr += ', ';
   		typestr += 'Other';
   	  }
      if (typestr != '') {
      	detailsDiv.appendChild(document.createTextNode("Type: " + typestr));
  	    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= "/afdc/locator/stations/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= "/afdc/locator/stations/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(onload) {
   // 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' ) {
      if(!onload) {
	 alert_str="Please Enter One or More Fuels from the Pick List";
	 alert(alert_str);
      }

      return(false);
   }

   return true;
}





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;
}

$(document).ready(function () {
	$('#fuels_ELEC').click(function() {
		if ($('#fuels_ELEC').attr("checked")) $('#electric_types').attr("style", "display:block");
		else $('#electric_types').attr("style", "display:none");
	});
	$('#help_1').qtip({
		content: {
			text: "<strong>Level 1</strong>: 120V (8-20 hours for a full charge)<br /><br /> \
				<strong>Level 2</strong>: 240V (3-8 hours for a full charge)<br /><br /> \
				<strong>DC Fast</strong>: 480V (<30 minutes for a full charge)<br /><br /> \
				<strong>Other</strong>: Includes all other charging equipment \
				including legacy systems, such as inductive \
				paddles. Select station details for more \
				information.<br /><br /> \
				 \
				<a href='/afdc/vehicles/electric_charging_equipment.html' target='_blank'>Learn more about charging equipment</a>. \
				",
		    title: {
		    	text: 'Station Types',
		        button: '<img src="/afdc/laws/images/close.gif" />',
				background: '#eee'
		    }
		},
		show: 'click',
		style: {
			width: 350,
			border: {
				width: 1,
				radius: 1,
				color: '#333'
			}
		},
		hide: {
			fixed: true,
			when: 'click'
		},

		position: {
			corner: {
				target: 'topRight',
				tooltip: 'leftTop'
			}
		}
	})
});

