// hbs-pap.js - logic for home birth services

var tabID = "hbs-ListTabs";
var mapTabID = "hbs-mapList";
var mapDivID = "hbs-mapDiv";
var indexID = "hbs-index";
var shortTableID = "hbs-short";
var longTableID = "hbs-long";

var hbsLocations = new Array();
var hbsMap; 

function MapChart(mapName) {
   this.map;
   
   if (GBrowserIsCompatible()) {
      this.map = new GMap2(document.getElementById(mapName));
      this.map.addControl(new GSmallMapControl());
      this.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
      this.myBounds = new GLatLngBounds();
   }
}

MapChart.prototype.map;
MapChart.prototype.myBounds;

MapChart.prototype.resetMap = function() {
   
   if (typeof this.map!="undefined")
   {
      this.map.checkResize();
      this.map.setZoom(this.map.getBoundsZoomLevel(this.myBounds) - 1);
      this.map.setCenter(this.myBounds.getCenter());
   }
}

MapChart.prototype.clearOverlays = function()
{
   if (typeof this.map!="undefined")
   {
      this.map.clearOverlays();
   }
}

MapChart.prototype.addOverlay = function(index, latitude, longitude, text)
{
   var letter = String.fromCharCode("A".charCodeAt(0) + index);
   var letteredIcon = new GIcon(baseIcon);
   letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
         
   var markerOptions = { icon:letteredIcon };
         
   var point = new GLatLng(latitude, longitude);
   var marker = new GMarker(point, markerOptions);
         
   this.myBounds.extend(point);
         
   marker.bindInfoWindowHtml(text);
         
   this.map.addOverlay(marker);

   
}




function hbsListLoad(page_index) {

   $("#" + shortTableID + " > .MCList").empty();
   $("#" + longTableID + " > .MCList").empty();
   $("#" + indexID).empty();
   
   if (hbsMap) { 
      hbsMap.clearOverlays();
   }
   hbsLocations = new Array();
   
   startSearch();
   var page_arg="page=" + (page_index || 1);
   var showRating_arg = "";
   if (showRating)
   {
      showRating_arg = "&showRating=true"
   }
   
   var hbsName = $("#scName").attr('value');
   var hbsName_arg = "";
   if (hbsName.length > 0)
   {
      hbsName_arg = "&name=" + hbsName;
   }

   $.ajax({
      url: '/national/html/custom/view/pap/papSearch.php5',
      type: 'GET',
      data: $("#searchForm").serialize() + "&" + page_arg + "&homeOnly=true&type=" + showRating_arg + hbsName_arg,
      dataType: 'xml',
      timeout: 5000,
      error: function(){
         alert('Error in retrieving providers.  Please Try again.');
      },
      success: function(xml){
         var ppage = parseInt($(xml).find('providerCollection').attr('page'));
         var pmax = parseInt($(xml).find('providerCollection').attr('max'));
         
         cssIndexID = "#" + indexID;
      
         if (pmax > 200)
         {
            alert("This search is too large.  Please redo your search again with narrower parameters.");
         }
         else
         {
            if (pmax > 0)
            {
               if (ppage > 1) { $('<a></a>').attr("page", ppage - 1).attr("href", "").html("Prev" ).appendTo(cssIndex).click(function () { listLoad($(this).attr("page")); return false; }); }
               $(cssIndexID).append(" ");
               if (25 < pmax)
               {     
                  for (index=1; index < (pmax+24)/25; index++)
                  {
                     if (index != ppage)
                     {
                        $('<a></a>').attr("page", index).attr("href", "").html(index).appendTo(cssIndexID).click(function () { listLoad($(this).attr("page")); return false; });
                     }
                     else
                     {
                        $('<span></span>').html(index).appendTo(cssIndexID);
                     }
                     $(cssIndexID).append(" ");
                  }
               }
               if (ppage < (pmax)/25) { $('<a></a>').attr("page", ppage + 1).attr("href", "").html("Next" ).appendTo(cssIndexID).click(function () { listLoad($(this).attr("page")); return false; }); }
               $(cssIndexID).append(" ");
               hbsLoadTable(xml, shortTableID, longTableID);
               searchTotal+= pmax;
            }
            else
            {
               alert("No Home Birth Service providers were found. Please widen your search and try again.\n\n\nClearing your previous search and searching by Zip code and 75 mile distance will give you the most results.\n\n\nIf you still do not find your provider click the 'Add a Provider' link.");
               $("#" + tabID).hide();
            }
            stopSearch();
         }
      }
   });
}


function hbsLoadTable(xml, tableName, tableLongName) {
   
   var tableID = '#' + tableLongName;
   var tableShortID = '#' + tableName;
   var entryCount = 0;
   var locIndex = 0;
   
   $(tableID + " tr.tBody ").remove();
   $(tableShortID + " tr.tBody ").remove();

   $(xml).find('provider').each(function(){
         
      var rowNum = $(this).attr("id");
      var fname = '';
      var lname = '';
      var mname = '';
      var title = '';
      var rowid = tableLongName + 'tr' + rowNum;
      var rowShortID = tableName + 'tr' + rowNum;
      entryCount++;
        
      $('<tr id="' + rowid + '" pid="' + rowNum + '"></tr>').appendTo(tableID).click(function() {
         $(this).siblings().removeClass("rowSelect");
         $(this).addClass("rowSelect");
         $("#ProviderID").val(rowNum); setPName(rowNum); });
      
      $('<tr id="' + rowShortID + '" pid="' + rowNum + '"></tr>').appendTo(tableShortID).click(function() {
         $(this).siblings().removeClass("rowSelect");
         $(this).addClass("rowSelect");
         $("#ProviderID").val(rowNum); setPName(rowNum); });

      if (showRating)
      {
         var latitude=-99999;
         var longitude=-99999;
         var address = "";
         var city = "";
         var state = "";
         var zipcode = "";
         var phone = "";
         $(this).find('latitude').each(function(){ latitude=$(this).text(); });
         $(this).find('longitude').each(function(){ longitude=$(this).text(); });
         $(this).find('address').each(function(){ address=$(this).text(); });
         $(this).find('city').each(function(){ city=$(this).text(); });
         $(this).find('state').each(function(){ state=$(this).text(); });
         $(this).find('zipcode').each(function(){ zipcode=$(this).text(); });
         $(this).find('phone').each(function(){ phone=$(this).text(); });
         
         hbsLocations[rowNum] = createLocation(latitude, longitude);
         hbsLocations[rowNum].rowIndex = locIndex;
         hbsLocations[rowNum].address = address + "<br>" + city + ", " + state + " " + zipcode;
         if (phone.length > 0)
         {
            phone = phone.substr(0, 3) + " " + phone.substr(3, 3) + "-" + phone.substr(6, 4);
            hbsLocations[rowNum].address += "<br>" + phone;
         }

         if (hbsLocations[rowNum].latitude != -99999)
         {
            var letter = String.fromCharCode("A".charCodeAt(0) + locIndex);
            locIndex++;
            $('<td></td>').html("<img src='http://www.google.com/mapfiles/marker" + letter + ".png'>").appendTo('tr#'+rowShortID);
         }
         else
         {
            $('<td></td>').html("&nbsp").appendTo('tr#'+rowShortID);
         }
      }

      $(this).find('lName').each(function(){lname=$(this).text();
         $('<td></td>').html(lname+"&nbsp").appendTo('tr#'+rowid);  });
      $(this).find('fName').each(function(){fname=$(this).text();
         $('<td></td>').html(fname+"&nbsp").appendTo('tr#' + rowid);  });
      $(this).find('mName').each(function(){mname=$(this).text();
         $('<td></td>').html(mname+"&nbsp").appendTo('tr#'+rowid);  });
      
      if (showRating)
      {
         date = "&nbsp";
         overall = "&nbsp";
         ocount = "&nbsp";
         
         hbsLocations[rowNum].name = fname + " " + mname + " " + lname;
         
         $(this).find('DATE').each(function() { date=$(this).text().substr(0,10); });
         $('<td></td>').html(date).appendTo('tr#'+rowid);
         
         $(this).find('OVERALLCOUNT').each(function() { ocount=$(this).text(); });
         
         viewImg="<img height='16px' width='77px'; onclick='submitProvider(" + rowNum + ")' src='/national/images/view_details.png'>";
         ocounttext="";
         if (ocount > 1) { ocounttext = "(" + ocount + " responses)";}
         else { ocounttext = "(" + ocount + " response)";}
         
         $(this).find('OVERALL').each(function() {
            overall='<img src="' + findStarImage($(this).text()) + '" style="float: left"\>';
            });
         $('<td align="center"></td>').html(overall).appendTo('tr#'+rowid);
         $('<td align="center"></td>').html("(" + ocount + " responses)").appendTo('tr#'+rowid);
         $('<td align="center"></td>').html(viewImg).appendTo('tr#'+rowid);
      
         var shortRowText = hbsLocations[rowNum].name;
         if (hbsLocations[rowNum].address)
         {
            shortRowText += "<br>" + hbsLocations[rowNum].address;
         }
      
         if (date != "&nbsp")
         {
            shortRowText += "<br>Last Survey: " + date + "&nbsp;&nbsp;&nbsp;&nbsp;" + ocounttext;
            shortRowText += "<br>" + overall + "&nbsp;&nbsp;&nbsp;&nbsp;" + viewImg;
         }
      
         $('<td></td>').html(shortRowText).appendTo('tr#'+rowShortID);
         
      }
      
      nameList[rowNum] = title + " " + fname + " " + lname;
      if (cpid==rowNum) {
         $("tr[pid='"+rowNum+"']").click();
         $("#Submitter").click();
      }

   });
   
   $(tableID + " > tbody *").addClass("tBody MCList");
   $(tableShortID + " > tbody *").addClass("tBody MCList");
   // Firefox 3 hack...
   if (entryCount < 8)
   {
      $('<tr class="tBody" ><td></td></tr>').appendTo(tableID);
   }
}


function createLocation(latitude, longitude) {
   
   var locObj = new Object();
   if (latitude == "") { latitude=-99999; }
   if (longitude == "") { longitude=-99999; }
   locObj.latitude=latitude;
   locObj.longitude=longitude;
   
   return locObj;
}

function hbsInitialize() {

   if (typeof hbsMap=="undefined")
   {
      hbsMap= new MapChart(mapDivID);
   }
      
   for (var loc in hbsLocations)
   {

      if (hbsLocations[loc].latitude != -99999)
      {
         hbsMap.addOverlay(hbsLocations[loc].rowIndex,
                           hbsLocations[loc].latitude,
                           hbsLocations[loc].longitude,
                           "<span style='font-size: 11px; font-family: Arial,Helvetica,sans-serif;' >" + hbsLocations[loc].name + "<br>" + hbsLocations[loc].address + "<br>" +
                           "<a href='' onClick='javascript:submitProvider(" + loc + "); return false;'>View Results</a></font>");
      }
   }
   
   hbsMap.resetMap();
}

function submitProvider(pid)
{
   if (pid)
   {
      window.open("providerOverall.shtml?pid="+pid);
   }
}


$(document).ready(function() {
   
      
   $("#DoSearch").bind("startSearch", function(e, myName, myValue) {
      if ($("#CheckHBS").is(":checked"))
      {
         $("#" + tabID).show();
         hbsLocations = new Array();
         hbsListLoad(1);
      }
      else
      {
         $("#" + tabID).hide();
      }
   });
   
   
   $("#" + tabID + " > ul").tabs({
      show : function(event, ui) {
         if (ui.panel.id == mapTabID) {
            if (typeof hbsMap!="undefined")
            {
               hbsMap.resetMap();
            }
         }
      }
   });
   
   $("#Results").bind("showResults", function(e, myName, myValue) {
      hbsInitialize();
   });
   
});