// pac.js - pac logic for pac.html
  
var nameList = [];
var previousProviders = ["java2X14X141","java2X15X265","java2X11X362","java2X11X363","java2X14X1033"];
var previousAnswers = ["answer2X14X141","answer2X15X265","answer2X11X362","answer2X11X363","answer2X14X1033"];

var map;
var myBounds;
var answerid;
var answerSet;
var cpid = 0;
var selectCid = -1;
var cidList = "";
var category = "";
var showRating = false;
var searchOnly = false;
var myLocations = new Array();
var totalSearchNum = 0;
var searchTotal = 0;

var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);


function findStarImage(rating)
{
   if (rating <= 0  ){rating_img = "/national/images/00star.gif";}
   if (rating >= 0.5){rating_img = "/national/images/05star.gif";}
   if (rating >= 1  ){rating_img = "/national/images/1star.gif";}
   if (rating >= 1.5){rating_img = "/national/images/15star.gif";}
   if (rating >= 2  ){rating_img = "/national/images/2star.gif";}
   if (rating >= 2.5){rating_img = "/national/images/25star.gif";}
   if (rating >= 3  ){rating_img = "/national/images/3star.gif";}
   if (rating >= 3.5){rating_img = "/national/images/35star.gif";}
   if (rating >= 4  ){rating_img = "/national/images/4star.gif";}
   if (rating >= 4.5){rating_img = "/national/images/45star.gif";}
   if (rating >= 5  ){rating_img = "/national/images/5star.gif";}
   
   return rating_img;
}


function validateSearchParms() {
   
   if (category.length == 0)
   {
      alert("Selecting at least one type of facility is required!")
      return false;
   }
   
   if (($("#sZipcode").val().length == 0) &&
       ((($("#sCity").val().length == 0) && ($("#scName").val().length == 0  )) || ($("#sState").val() == "00")))
   {
      alert("A Zipcode or City/State Selection is required to begin a search!");
      return false;
   }
   return true;
}

function setPName(index) {
   selectCid = index;
}

function setCategory() {
   
   if (searchOnly)
   {
      var categories = new Array();
      if ($("#CheckHospital").is(":checked")) { categories.push("Hospital"); }
      if ($("#CheckHSBC").is(":checked")) { categories.push("HSBC"); }
      if ($("#CheckFSBC").is(":checked")) { categories.push("FSBC"); }
      if ($("#CheckPractice").is(":checked")) { categories.push("Practice"); }
      if ($("#CheckHBS").is(":checked")) { categories.push("HBS"); }
   
      category = categories.join(",");
   }
   
}



function prevLoad() {

   $("#PreviousSelect").fadeOut("fast", function() {
      $("#PreviousSelect").hide();
      $("#Loading").fadeIn("slow"); 
      $("#pcl > .MCList").empty();
      
      $.ajax({
         url: 'pacPrev.php5',
         type: 'GET',
         data: cidList,
         dataType: 'xml',
         timeout: 5000,
         error: function(){
            alert('Error loading previous centers.  Please search for your center again or try again later.');
            $("#Loading").fadeOut("slow", function () {  $("#Loading").hide(); $("#Search").fadeIn("fast");  })
         },
         success: function(xml){
           loadPTable(xml, '', 'pcl');
           $("#Loading").fadeOut("slow", function () {  $("#Loading").hide(); $("#PreviousSelect").fadeIn("fast", resetTable);  })
         }
      });
   });
}


function listLoad(page_index) {

      $("#spl > .MCList").empty();
      $('#spl-index').empty();
      
      clearSearch();
      startSearch();
      var page_arg="page=" + (page_index || 1);
      var showRating_arg = "";
      if (showRating)
      {
         showRating_arg = "&showRating=true"
      }
      
      $.ajax({
         url: '/national/html/custom/view/pac/pacSearch.php5',
         type: 'GET',
         data: $("#searchForm").serialize() + "&" + page_arg + "&type=" + category + showRating_arg,
         dataType: 'xml',
         timeout: 5000,
         error: function(){
            alert('Error in retrieving centers.  Please Try again.');
            stopSearch();
         },
         success: function(xml){
            var ppage = parseInt($(xml).find('centerCollection').attr('page'));
            var pmax = parseInt($(xml).find('centerCollection').attr('max'));
         
            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('#spl-index').click(function () { listLoad($(this).attr("page")); return false; }); }
                  $('#spl-index').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('#spl-index').click(function () { listLoad($(this).attr("page")); return false; });
                        }
                        else
                        {
                           $('<span></span>').html(index).appendTo('#spl-index');
                        }
                        $('#spl-index').append(" ");
                     }
                  }
                  if (ppage < (pmax)/25) { $('<a></a>').attr("page", ppage + 1).attr("href", "").html("Next" ).appendTo('#spl-index').click(function () { listLoad($(this).attr("page")); return false; }); }
                  $('#spl-index').append(" ");
                  loadPTable(xml, 'spl-short', 'spl-long');
                  searchTotal += pmax;
               }
               else
               {
                  $("#Loading").fadeOut("slow", function () {
                     alert("No facilities 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 facility click the 'Add a Facility' link.");
                     if (!searchOnly)
                     {
                        $("#CenterName").html("No facilities were found.  Please widen your search and try again or ").addClass("alarmMsg");
                        $("<a></a>").html("Add a Facility.").addClass("hotlink").appendTo("#CenterName").click(function () {
                           $("#Search").slideUp("fast", function() { $("#AddCenter").slideDown(); $("#CenterName").html("");}) });
                     }
                     $("#cListTabs").hide();
                  });
               }
            }
            stopSearch();
         }
      });
}

jQuery.validator.addMethod("ziprange", function(value, element) {
   return this.optional(element) || /^\d{5}-?(\d{4})?$/.test(value);
}, "Your ZIP-code must be formated XXXXX or XXXXX-XXXX");

jQuery.validator.addMethod("stateList", function(value, element) {
   return this.optional(element) || (value != "00");
}, "Please Select a state from the menu list.");

function addLatitude(latitude, longitude, index) {
   
   var locObj = new Object();
   if (latitude == "") { latitude=-99999; }
   if (longitude == "") { longitude=-99999; }
   locObj.latitude=latitude;
   locObj.longitude=longitude;
   myLocations[index] = locObj;
   
   return locObj;
}

function clearSearch()
{
   if (map) {
      map.clearOverlays();
   }
   
   myLocations = new Array();
   searchTotal = 0;
}


function loadPTable(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('center').each(function(){
         
      var rowNum = $(this).attr("id");
      var name = '';
      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");
         $("#CenterID").val(rowNum);
         setPName(rowNum); });
      
      $('<tr id="' + rowShortID + '" pid="' + rowNum + '"></tr>').appendTo(tableShortID).click(function() {
         $(this).siblings().removeClass("rowSelect");
         $(this).addClass("rowSelect");
         $("#CenterID").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(); });
      
         var locObj = addLatitude(latitude, longitude, rowNum);
         myLocations[rowNum].rowIndex = locIndex;
         myLocations[rowNum].address = address + "<br>" + city + ", " + state + " " + zipcode;
         if (phone.length > 0)
         {
            phone = phone.substr(0, 3) + " " + phone.substr(3, 3) + "-" + phone.substr(6, 4);
            myLocations[rowNum].address += "<br>" + phone;
         }

         if (locObj.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('name').each(function(){name=$(this).text();
         $('<td></td>').html(name+"&nbsp").appendTo('tr#'+rowid);  });
      $(this).find('city').each(function(){city=$(this).text();
         $('<td></td>').html(city+"&nbsp").appendTo('tr#'+rowid);  });

      
      if (showRating)
      {
         date = "&nbsp";
         overall = "&nbsp";
         ocount = "0";
         
         myLocations[rowNum].name = name;
         
         $(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='submitCenter(" + 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(ocounttext).appendTo('tr#'+rowid);
         $('<td align="center"></td>').html(viewImg).appendTo('tr#'+rowid);
      
         var shortRowText = myLocations[rowNum].name;
         if (myLocations[rowNum].address)
         {
            shortRowText += "<br>" + myLocations[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] = name;
      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 addCenter () {
   
   if ($("#addForm").valid()){
   
      $("#Add").attr("disabled", true);
      $.ajax({
         url: 'pacAdd.php5',
         type: 'GET',
         data: $("#addForm").serialize(),
         dataType: 'xml',
         timeout: 5000,
         error: function(){
            alert('Error adding center.  Please try again.');
            $("#Add").removeAttr("disabled");
         },
         success: function(xml){
            $(xml).find('Success').each(function(){
               $("#addMsg").html("You have successfully added " + $("#acName").val());
               nameList[$(this).text()] = $("#acName").val();
               submitCenter($(this).text());
               setPName(0);
            });
            $(xml).find('Failure').each(function(){
               alert($(this).text());
            });
            $("#Add").removeAttr("disabled");
         }
      });
   }
}

function submitCenter(cid)
{
   if (cid == -1)
   {
      $("#CenterName").html("You have specified that your center be Anonymous.");
   }
   else if (cid == 0)
   {
      $("#CenterName").html("");
   }
   else
   {
      $("#CenterName").html("You have selected " + nameList[cid]);
   }
   $("#CenterName").removeClass("alarmMsg");
   
   if (self.parent.document.getElementById(answerSet))
   {
      self.parent.document.getElementById(answerSet).value=cid;
   }
   cpid = cid;
}



function resetTable() {
   $(".rowSelect").each(function () { if ($(this).attr("pid") != cpid) { $(this).removeClass("rowSelect"); } });
   selectCid = cpid;
}


function initialize() {

   if (GBrowserIsCompatible() && searchOnly) {
      if (!map)
      {
         map = new GMap2(document.getElementById("mapDiv"));
         map.addControl(new GSmallMapControl());
         map.setCenter(new GLatLng(37.4419, -122.1419), 13);         
         var geocoder = new GClientGeocoder();
      }
      else
      {
         map.checkResize();
      }
      myBounds = new GLatLngBounds();
      
      
      var resetMap = false;
      for (var loc in myLocations)
      {
         if (myLocations[loc].latitude > -399)
         {
            var letter = String.fromCharCode("A".charCodeAt(0) + myLocations[loc].rowIndex);
            var letteredIcon = new GIcon(baseIcon);
            letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
            
            var markerOptions = { icon:letteredIcon };
            
            var point = new GLatLng(myLocations[loc].latitude, myLocations[loc].longitude);
            var marker = new GMarker(point, markerOptions);
            
            myBounds.extend(point);
            
            marker.bindInfoWindowHtml("<span style='font-size: 11px; font-family: Arial,Helvetica,sans-serif;' >" + myLocations[loc].name + "<br>" + myLocations[loc].address + "<br>" +
                                      "<a href='' onClick='javascript:submitProvider(" + loc + "); return false;'>View Results</a></font>");
            
            map.addOverlay(marker);
            resetMap = true;
         }
      }
      
      if (resetMap)
      {
         map.setZoom(map.getBoundsZoomLevel(myBounds) - 1  );
         map.setCenter(myBounds.getCenter());
      }
   }
}

function startSearch()
{
   totalSearchNum++;
}

function stopSearch()
{
   totalSearchNum--;
   if (totalSearchNum == 0)
   {
      $("#DoSearch").trigger("stopSearch");;
   }
}



$(document).ready(function() {

   answerid = $(document).getUrlParam("AnswerSet");
   category = $(document).getUrlParam("Category");
   skipPrev = $(document).getUrlParam("SkipPrev");
   searchOnly = $(document).getUrlParam("SearchOnly");
   showRating = $(document).getUrlParam("ShowRating");
   answerSet = 'answer' + answerid;
   
   if (searchOnly)
   {
      $(".Anonymous").hide();
      $(".AddCenter").hide();
      $(".Submitter").hide();
   }
   
   var pinput = self.parent.document.getElementById(answerSet);
   if (pinput)
   {
      pinput.readOnly='false';
      pinput.style.display = 'none';
      cpid = pinput.value;
   }
   
   if (!skipPrev)
   {
      $("body", parent.document).find("input").each(function () {
         var cid = -1;
         if (((cid = jQuery.inArray($(this).attr("id"), previousProviders)) != -1) ||
             ((cid = jQuery.inArray($(this).attr("id"), previousAnswers)) != -1))
         {
            var valId = $(this).attr("value");
            if (valId > 0)
            {
               cidList = cidList + valId + ",";
            }
         }
      });
   }
   else
   {
      cidList = cpid;
   }
   
   if (cidList.length > 0)
   {
      cidList = "data=" + cidList;
      $("#Search").hide();
      prevLoad();
   }
   else
   {
      $("#PrevSelect").hide();
      $("#PreviousSelect").hide();
      $("#Loading").hide();
   }
   
   if (category)
   {
      $(".CenterCategory").hide();
   }
   
   if (!showRating)
   {
      $(".CenterRating").hide();
   }
   
   $("#addForm").validate(); // Setup Validation for Add form

   $("#Results").hide();
   $("#AddCenter").hide();

   $("#DoSearch").click(function () {
      if (validateSearchParms())
      {
         $("#Search").fadeOut("fast", function() {
            $("#Loading").fadeIn("slow"); 
         
            $("#DoSearch").trigger("startSearch");
         });
      }
   });
   
   
   $("#DoSearch").bind("startSearch", function(e, myName, myValue) {
      if ($("#CheckHospital").is(":checked") || $("#CheckHSBC").is(":checked") ||
          $("#CheckFSBC").is(":checked") || (!searchOnly))
      {
         $("#cListTabs").show();
         submitCenter("");
         selectCid = "";
         listLoad(1);
      }
      else
      {
         $("#cListTabs").hide();
      }
   });
   
   $("#DoSearch").bind("stopSearch", function(e, myName, myValue) {
      if (searchTotal > 0)
      {
         $("#Loading").fadeOut("slow",
                         function () { $("#Results").fadeIn("fast",
                                                            function () { $("#Results").trigger("showResults"); });  });
      }
      else
      {
         $("#Loading").hide();
         $("#Search").fadeIn("fast");
      }
   });
   
   
   $("#Add").click(addCenter);  // Set the Add submit button to the add Provider 
   $("#NotListed").click(function () {
      $("#Results").slideUp("fast", function () { $("#AddCenter").slideDown(); });
   });
   $("#Back").click(function () {
      $("#AddCenter").slideUp("fast", function () { $("#Search").slideDown("fast"); });
   });
   $("#RedoSearch").click(function () {
      $("#Results").fadeOut("fast", function () {$("#Search").fadeIn("fast"); clearSearch(); }); 
   });
   $("#StartSearch").click(function() {
      $("#PreviousSelect").slideUp("fast", function () { $("#Search").slideDown(); });
   });
   $("#PrevSelect").click(function() {
      $("#Search").slideUp("fast", function() { $("#PreviousSelect").slideDown("fast", resetTable); });
   });
   $(".Submitter").click(function () {
      if (selectCid > 0)
      {
         submitCenter(selectCid);
      }
      else
      {
         $("#CenterName").html("You have not specified a center!");
      }
   });
   
   $(".Anonymous").click(function () {
      submitCenter(-1);
   });
   
   $("#DoClear").click(function () {
      $('.search').val("");
   });

   setCategory();
   $("#CheckHospital").click(setCategory);
   $("#CheckHSBC").click(setCategory);
   $("#CheckFSBC").click(setCategory);
   $("#CheckHBS").click(setCategory);
   $("#CheckPractice").click(setCategory);
   
   if (cpid==-1) { $(".Anonymous").click(); }
   
   if (searchOnly) {
      $("#cListTabs > ul").tabs({
         
         show : function(event, ui) {
            if ((ui.panel.id == "mapList") && (typeof map!="undefined")) {
               map.checkResize();
               map.setZoom(map.getBoundsZoomLevel(myBounds) - 1);
               map.setCenter(myBounds.getCenter());
            }
         }
      });
   }
   
   $("#Results").bind("showResults", function(e, myName, myValue) {
      initialize();
   });
   
   
   $('#selectAll').click( function() { $('.centerType').attr('checked', true); });
   $('#selectNone').click( function() { $('.centerType').attr('checked', false); });

   window.onbeforeunload = function () {
      if (searchTotal > 0) {
         return "You are about to loose all your search parameters and results.  Do you wish to continue?";
      }
   }

});
