// *********** LEFT NAV BAR

// default text for the location input boxes
var defaultLocationText = 'Zip or City, State/Prov';

// properties for all Petfinder cookies (the ones that use YUI, anyway)
var cookieProps = { 
  domain:  "petfinder.com",
  expires: exp,
  path: "/"
};

// stores the list of pet IDs from the search results page
// for use later within the pet notes page - for next/prev pagination
// EXCEPT the first and last items in this array are links 
// to the search results next or previous pages
var pet_pag_links      = [];

// when viewing the first or last pet note page from a 
// search results page, if there is a link to the previous or next
// pet note page, respectively, the following arrays will contain the 
// AJAX-fetched list of prev/next search results links.
// Then, when a user clicks prev/next, the pet_pag_links variable
// is replaced with the contents of one of the following arrays.
var prev_pet_pag_links = [];
var next_pet_pag_links = [];

// This is the namespace for all Petfinder search attributes and subroutines -
// used for YUI stuff
YAHOO.namespace('PF.search');

// showLoadingBox will display a modal panel containing a "Loading" box.
function showLoadingBox() {
	
  // only initialize the wait panel once; if has already been used once
  // on this page, there is no need to re-initialize it.  we can just hide/show
  // it as needed.
  if (!YAHOO.PF.search.wait) { 	
  
    // Initialize the temporary Panel to display while waiting for external content to load
    YAHOO.PF.search.wait = new YAHOO.widget.Panel("wait", { 
      width:"240px", 
      fixedcenter:true, 
      close:false, 
      draggable:false, 
      zindex:4000,
      modal:true,
      visible:false
    });
    YAHOO.PF.search.wait.setHeader("Loading, please wait...");
    YAHOO.PF.search.wait.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />');
    YAHOO.PF.search.wait.render(document.body);
  }
  YAHOO.PF.search.wait.show();
}

// hideLoadingBox will hide the modal panel with a "Loading" box
// but won't completely get rid of it; that way we can use it again
// if needed.
function hideLoadingBox() {
  YAHOO.PF.search.wait.hide();      
}

// showMainOptions is the onClick event for the 'change' link on the 
// left bar of a search results page
var showMainOptions = function() { 

  // this cookie contains pre-saved user search information
  // we'll use it to pre-fill the location and animal form fields
  var cookieSubs = YAHOO.util.Cookie.getSubs('search', cookieProps);
  
  // load location from cookie
  if (cookieSubs.location && (cookieSubs.location !== '') && document.getElementById('pet-location') ) {
    document.getElementById('pet-location').value = cookieSubs.location;
  }

  // load animal type from cookie
  if (cookieSubs.animal && (cookieSubs.animal !== '') ) {
    animalObj = document.getElementById('animal_type');
    for (i in animalObj.options) {
      if (animalObj.options[i] && animalObj.options[i].text && animalObj.options[i].text == cookieSubs.animal) {
        animalObj.selectedIndex = i;
        break;
      }
    }
  }

  // switch out CSS classes for the "change" effect
  
  // show the hidden animal type/location form
  YAHOO.util.Dom.addClass('location-hidden', 'show-options'); 

  // hide the 'Dogs near 84062 [change]'
  // and all refinements
  YAHOO.util.Dom.addClass('search-info', 'hide');
  YAHOO.util.Dom.addClass('refinements', 'hide');
}; 

// hideMainOptions() is the onClick event for the 'close' link 
// shown after clicking the 'change' link in the left rail
// of a search results page
var hideMainOptions = function() { 

  // remove CSS classes added during showMainOptions() for the "close" effect
  
  // hide the hidden animal type/location form
  YAHOO.util.Dom.removeClass('location-hidden', 'show-options'); 

  // show the 'Dogs near 84062 [change]'
  // and all refinements
  YAHOO.util.Dom.removeClass('search-info', 'hide');
  YAHOO.util.Dom.removeClass('refinements', 'hide');
}; 

// register the showMainOptions() and hideMainOptions() events
// with their appropriate links ("change" and "close", respectively)
YAHOO.util.Event.on('location-show', 'click', showMainOptions);
YAHOO.util.Event.on('x', 'click', hideMainOptions); 

// clearSearchLocation() is the onfocus event for the pet-location input.
// When the location field contains the default location text,
// we need to get rid of it as soon as the browser's focus is on the box
function clearSearchLocation() {
  var search = document.getElementById("search-form");
  if(search.location && search.location.value && (search.location.value == defaultLocationText) ) {
    search.location.value = "";
  }
}

// doSearch() is the onclick event for search refinements
function doSearch(e) {

  // use the YUI Browser History Manager to navigate to the proper search results partial page
  try {	
    YAHOO.util.History.navigate("pet-search", "results-" + this.value);
  }
  catch(e) {

    // this should never happen, but just in case history isn't working we can
    // bypass it and load the partial search results page directly
    displayPartialSearchResults(this.value);
  }  
}

// doSearchLink() is the onclick event for search links - prev/next mostly
function doSearchLink(e) {
	
  // strip the domain and path from the state value - if present
  // the state value comes from the next/prev link's href attribute
  var target = this.href;
  if (target.indexOf('http://' + window.location.hostname) >= 0) {
    target = target.substring(target.indexOf(window.location.hostname) + window.location.hostname.length);
  }
  if (target.indexOf('/pet-search?') >= 0) {
    target = target.substring(target.indexOf('/pet-search?') + 12);
  }
  
  // use YUI Browser History Manager to navigate to the proper search results partial page
  try {	
    YAHOO.util.History.navigate("pet-search", "results-" + target);
  }
  catch(e) {

    // this should never happen, but just in case history isn't working we can
    // bypass it and load the partial search results page directly
    displayPartialSearchResults(target);
  }
}

// submitBreed() is the onclick event called when un-checking a previously added
// pet breed refinement.
function submitBreed(newurl) {

  // strip leading path off of state value, if present
  var target = newurl;
  if (target.indexOf('/pet-search?') >= 0) {
    target = target.substring(target.indexOf('/pet-search?') + 12);
  }

  // use the YUI Browser History Manager to navigate to the proper search results partial page
  try {	
    YAHOO.util.History.navigate("pet-search", "results-" + target);
  }
  catch(e) {

    // this should never happen, but just in case history isn't working we can
    // bypass it and load the partial search results page directly
    displayPartialSearchResults(target);
  }
}

// selectDistance() is the onchange listener for the distance select box
function selectDistance() {
  
  // first check to be sure the element exists as we want it to; 
  // there's a chance it won't and we don't want the browser to throw an error
  var list = document.getElementById('distance');
  if (list.options) {

    // strip the leading path info off of the state value, if present
    var target = list.options[list.selectedIndex].value; 
    if (target.indexOf('pet-search=results-') >= 0) {
      target =  target.substring(target.indexOf('results-') + 8);
    }
    else if (target.indexOf('/pet-search?') >= 0) {
      target = target.substring(target.indexOf('/pet-search?') + 12);
    }
    
    // use the YUI Browser History Manager to navigate to the proper search results partial page
    try {	
      YAHOO.util.History.navigate("pet-search", "results-" + target);
    }
    catch(e) {

      // this should never happen, but just in case history isn't working we can
      // bypass it and load the partial search results page directly
      displayPartialSearchResults(target); 
    }
  }
}

// clickPetNote() is the onclick event for pet note links on search results pages
function clickPetNote() {

  // use the YUI Browser History Manager to navigate to the proper pet note partial page
  try {	
    YAHOO.util.History.navigate("pet-search", "pet-" + this.href.substring(this.href.indexOf('=')+1));
  }
  catch(e) {

    // this should never happen, but just in case history isn't working we can
    // bypass it and load the partial pet note directly
    displayPetNote('http://' + window.location.hostname + '/petdetail/' + this.href.substring(this.href.indexOf('=')+1));
  }
}

// returnToSearchResults() is the onclick event for "Return to Search Results" links on pet notes pages
function returnToSearchResults() {
	
  // first, strip off unwanted text from the front of the the state value, if present
  var target = YAHOO.util.Cookie.get('searchUrl', cookieProps);
  if (target.lastIndexOf(window.location.hostname) >= 0) {
    target = target.substring(target.lastIndexOf(window.location.hostname) + window.location.hostname.length);
  }
  if (target.lastIndexOf('/pet-search?') >= 0) {
    target = target.substring(target.lastIndexOf('/pet-search?') + 12);
  }
  
  // navigate to the search results page
  YAHOO.util.History.navigate("pet-search", "results-" + target);

  return false;
}

// displayPetNote() is called by the YUI Browser Manager to change to a partial pet note page
function displayPetNote(url) {

  // set up an AJAX request to get HTML for the partial pet note
  YAHOO.util.Connect.asyncRequest('GET', url, {

    // the browser will wait until after the partial pet note's HTML is loaded
    // to call this function
    success: function(o) {

      // for prefetching the next pet
      var nextPetId = 0;
      
      // write the pet detail stuff to the center of the page.
      // there's a bunch of stuff in hidden divs that we'll use later.
      var div = document.getElementById('search_content');
      div.innerHTML = o.responseText;

      // update the pagination.  this section is a beast.
      
      // get the pet ID from the AJAX url
      var pet_part = /\/(\d+)$/;
      var result = pet_part.exec(url);
      var pet_id = (result.length > 0) ? result[1] : 0;

      // for next/prev pagination
      var next, previous;
      var prev_url = '';
      var next_url = '';

      // set up the onclick event listener for the "Return to Search Results" link
      YAHOO.util.Event.addListener(document.getElementById('search-results-link'), 'click', returnToSearchResults);
      
      // update the pet's permalink with the pet ID
      document.getElementById('pet-permalink').href = 'http://' + window.location.hostname + '/pet-search?petid=' + pet_id;

      // set up the navigation div
      var div2 = document.getElementById('pet_note_nav');
      div2.style.display = 'block';
      
      // hide the links div (it's within the navigation div) until we're done resetting it
      var links_div = document.getElementById('pet_pagination');
      links_div.style.visibility = 'hidden';
      links_div.style.display    = 'none';

      // iterate throught the pet_pag_links array (it contains pet IDs) until we find the pet we just loaded
      for (var i = 1; i < pet_pag_links.length; i++) {
        if ( pet_id == pet_pag_links[i] ) {
	
          // set up the next/previous variables
          previous = pet_pag_links[i - 1];
          next = pet_pag_links[i + 1];
          var links = '';

          // if we're at the first element in the list, the 'previous' should be greyed out
          if ( i == 1 ) {
	          
            // if we're not on the very first search results page, we'll later add some fancy stuff 
            // to pre-fetch the previous pet_pag_links when the user clicks the prev link
            if (previous !== '') {
              links += '<a href="http://' + window.location.hostname + '/pet-search?' + previous.replace('&amp;partial=true','') + 
                '" id="prev-pet-link"><img alt="" src="http://mary.dev.petfinder.com/images/design/prev_gray.jpg" /></a> ';
              prev_url = previous.replace('&amp;partial=true','') + '&amp;pagination=1';
            }
            
            // if we're on the ver first search results page, there's no previous page.
            else {
              links += '<img alt="" src="http://mary.dev.petfinder.com/images/design/prev_gray.jpg" />';
            }
          }
          
          // add a link to the previous pet in the list
          else {
            links += '<a class="petlink" href="http://' + window.location.hostname + '/pet-search?petid=' + previous + 
                '" onclick="return false;" id="prev-pet-link"><img src="http://www.petfinder.com/images/design/prev.jpg" alt="" /></a> ';
          }

          links += '&nbsp;&nbsp;&nbsp;&nbsp;';

          // last pet is 2 from end because the LAST link is a URL
          if ( i == pet_pag_links.length - 2 ) {
	          
            // if we're at the end of the list and there's another search results page, we set up
            // things to pre-fetch the next pet_pag_links later on
            if (next !== '') {
              links += '<a href="http://' + window.location.hostname + '/pet-search?' + next.replace('&amp;partial=true','') + 
                '" id="next-pet-link"><img alt="" src="http://mary.dev.petfinder.com/images/design/next_gray.jpg" /></a>';
              next_url = next.replace('&amp;partial=true','') + '&amp;pagination=1';
            }
            
            // if we're at the end of the list on the very last search results page there won't be a next link
            else {
              links += '<img alt="" src="http://mary.dev.petfinder.com/images/design/next_gray.jpg" />';
            }
          }
          
          // add a link to the next pet in the list
          else {
            links += '<a class="petlink" href="http://' + window.location.hostname + '/pet-search?petid=' + next + 
                '" onclick="return false;" id="next-pet-link"><img src="http://www.petfinder.com/images/design/next.jpg" alt="" /></a>';
                
            // we'll use this later to prefetch the next pet right after we show this pet
            nextPetId = next;
          }

          // add the links to the DOM
          links_div.innerHTML = links;
          
          // we are do these things here because we have to wait until the links string have been added to the DOM
          
          // prefetch the next_pet_pag_links so we can replace pet_pag_links with it when the user clicks 'next'
          if (next_url) {
            YAHOO.util.Connect.asyncRequest('GET', 'http://' + window.location.hostname + '/pet-search?' + next_url, {
              success: function(next_o) {
                var obj = eval( '(' + next_o.responseText + ')' );
                var pet;
                
                // iterate through pets to update the next_pet_pag_links variable
                next_pet_pag_links = [];
                for( pet in obj.pets ) {
                  next_pet_pag_links.push(obj.pets[pet]);
                }
                
                // replace the greyed out "next" button with a new one
                document.getElementById('next-pet-link').innerHTML = 
                  '<img src="http://www.petfinder.com/images/design/next.jpg" alt="" />';
                document.getElementById('next-pet-link').onclick = function() { return nextPetLink(next_pet_pag_links[1]); };
                document.getElementById('next-pet-link').href = 
                  'http://' + window.location.hostname + '/pet-search?petid=' + next_pet_pag_links[1];
                  
                // we'll use this later to prefetch the next pet right after we show this pet
                nextPetId = next_pet_pag_links[1];
                
                // after we've finished with next_pet_pag_links, we can show the links div
                links_div.style.visibility = 'visible';
                links_div.style.display    = 'block';
              },
              failure: function(o) {

                // if it failed for some odd reason, gracefully show the links div
                links_div.style.visibility = 'visible';
                links_div.style.display    = 'block';
              }
            });
          }
          
          // prefetch the prev_pet_pag_links so we can replace pet_pag_links with it when the user clicks 'previous'
          if (prev_url) {
            YAHOO.util.Connect.asyncRequest('GET', 'http://' + window.location.hostname + '/pet-search?' + prev_url, {
              success: function(prev_o) {
                var obj = eval( '(' + prev_o.responseText + ')' );
                var pet;

                // iterate through pets to update the pet_pag_links variable
                prev_pet_pag_links = [];
                for( pet in obj.pets ) {
                  prev_pet_pag_links.push(obj.pets[pet]);
                }
                
                // replace the greyed out "previous" button with a new one
                document.getElementById('prev-pet-link').innerHTML = 
                  '<img src="http://www.petfinder.com/images/design/prev.jpg" alt="" />';
                document.getElementById('prev-pet-link').onclick = function() { return prevPetLink(prev_pet_pag_links[25]); };
                document.getElementById('prev-pet-link').href = 
                  'http://' + window.location.hostname + '/pet-search?petid=' + prev_pet_pag_links[25];
                  
                // we don't prefetch the previous pet (like we did for the next pet)
                // because the user most likely already viewed it
                
                // after we've finished with the prev_pet_pag_links, we can show the links div
                links_div.style.visibility = 'visible';
                links_div.style.display    = 'block';
              },
              failure: function(o) {
	              
                // if it failed for some odd reason, gracefully show the links div
                links_div.style.visibility = 'visible';
                links_div.style.display    = 'block';
              }
            });
          }
          
        }
      }
      
      // if we were on a normal page (in the middle of the 25 search results pages),
      // show the next/prev links immediately (no more ajax)
      if ( (prev_url == '') && (next_url == '') ) {
        links_div.style.visibility = 'visible';
        links_div.style.display    = 'block';
      }
      
      // fix up the pet note right rail
      showPetnoteRail();
      
      // update the ads - this is a new page
      loadPetAds();

      // this will update the pet stats we report to the shelters.
      // no need for success/failure because it doesn't matter what is returned
      YAHOO.util.Connect.asyncRequest('GET', document.getElementById('log-url').innerHTML.replace(/&amp;/g, '&'));

      // set up the onclick events for the prev/next links
      YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('petlink'), 'click', clickPetNote);
      
      // update google analytics
      pageTracker._trackPageview('petnote');
      
      // load the pet video, if present
      loadVideo();
      
      // TODO: fix the photo base parameter
      // and now I forget what that TODO note meant
      
      // load the recent pets
      loadRecentPets('recentpets-container', 'Recently Viewed Pets');
      
      // add this pet to the recent pet list using pet data from our hidden divs
      addToRecentPets(pet_id, document.getElementById('petnote-shelterid').innerHTML, 
        document.getElementById('petnote-status').innerHTML, document.getElementById('petnote-name').innerHTML);
      
      // update the page title using pet data from our hidden div
      document.title = document.getElementById('new-title').innerHTML;
      
      // display the refinements and distance divs... they will be hidden if
      // we're coming directly to this page from a bookmark using the 
      // YUI Browser History Manager
      YAHOO.util.Dom.addClass('refinements', 'unhide');
      YAHOO.util.Dom.addClass('distance', 'unhide');

      // scroll to the top of the page to mimick usability of a new page load
      window.scroll(0,0);
      
      // we can finally prefetch the next pet in the list if present
      if (nextPetId > 0) {
        fetchPet(nextPetId);
      }
    },
    
    // if the AJAX request fails, do this.
    // TODO: display a better "request failed" page
    failure: function(o) {
      var div = document.getElementById('search_content');
      div.innerHTML = 'Could not fetch Pet Note: ' + o.status + ' ' + o.statusText;
    }
  });
}

// prevPetLink() is the onclick event for clicking on a previous pet in the list IF we're at
// the first pet on the search results page, because then we have to 
// update the pet_pag_links variable with the list of pets on the previous page
// (we prefetched it when we displayed the pet)
function prevPetLink(petid) {
    pet_pag_links = prev_pet_pag_links;
    YAHOO.util.History.navigate("pet-search", "pet-" + petid);
    return false;
}

// nextPetLink() is the onclick event for clicking on a next pet in the list IF we're at
// the last pet on the search results page, because then we have to 
// update the pet_pag_links variable with the list of pets on the next page
// (we prefetched it when we displayed the pet)
function nextPetLink(petid) {
    pet_pag_links = next_pet_pag_links;
    YAHOO.util.History.navigate("pet-search", "pet-" + petid);
    return false;
}

// displayPartialSearchResults() is called by the YUI Browser Manager to change to a
// partial search results page
function displayPartialSearchResults(url) {
  
  // strip off extra info we don't want from the url - just in case it's there (it shouldn't be)
  // we tried to do this before calling the YUI Browser History Manager so the URL wouldn't be so long,
  // but you never know if these slipped through.
  url = url.replace('/pet-search?', '');
  url = url.replace('&partial=true', '');
  if (url.indexOf('#') > 0) {
    url = url.substring(0, url.indexOf('#'));
  }

  // show the wait panel so users can't click refinements while we're working on this new page
  showLoadingBox();
  
  // 
  saveSearchCookie('http://' + window.location.hostname + '/pet-search?' + url);
  YAHOO.util.Connect.asyncRequest('GET', 'http://' + window.location.hostname + '/pet-search?' + url + '&partial=true', {
    success: function(o) {
    
      // write the search results stuff to the center of the page
      var div = document.getElementById('search_content');
      div.innerHTML = o.responseText;
      if (document.getElementById('new-guided-nav')) {
        document.getElementById('guided-nav').innerHTML = document.getElementById('new-guided-nav').innerHTML;
      }

      // switch out the right rail
      showResultsRail();
      showBannerAd();

      // empty the pet pagination status bar
      //document.getElementById('pet_note_nav').innerHTML = '';
      document.getElementById('pet_note_nav').style.display = 'none';      
      
      // update page tracking/ad stuff
      pageTracker._trackPageview('pet-search-results');
      
      
      // register page results view with YUI Browser History Manager
      //document.title = document.getElementById('new-title').innerHTML;
      displaySearchResults();
      YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('petlink'), 'click', clickPetNote);
      YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('search-link'), 'click', doSearchLink);    
      YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('dimsearch'), 'click', doSearch);
      YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('pet-name-search'), 'click', clickPetNote);
      YAHOO.util.Event.addListener('distance', 'change', selectDistance);
      
      // pet_pag_links based on the li elements within 
      // update pet_pag_links since it's relative to the search results page (it's used in pet notes, BTW)
      // use the li elements within ul#page-links
      pet_pag_links = [];
      if (document.getElementById('page-links')) {
        var links = document.getElementById('page-links').childNodes;
        for(var i = 0; i < links.length; i++) {
          pet_pag_links.push(links[i].innerHTML);
        }
      }
      YAHOO.util.Event.on('location-show', 'click', showMainOptions);
      YAHOO.util.Event.on('x', 'click', hideMainOptions); 
      
      hideLoadingBox();
      
      var animal = document.getElementById('animal_type').options[document.getElementById('animal_type').selectedIndex].value;
      animal = animal.replace('&', '');      

      // create the two iframe ad elements and add them to the dom
      document.getElementById('banner_ad').innerHTML = '<iframe src="/banner-ad.html?sitepage=searchresults&amp;keyword=' + animal + 
       '" width="728px" height="90px" ' +
       ' marginheight="0px" marginwidth="0px" scrolling="no" frameborder="0" ' +
       ' style="width: 728px; height: 90px; margin: 0px; padding: 0px; border: 0px;"> ' +
       '</iframe>';

      document.getElementById('ad_bar_ad').innerHTML = '<iframe src="/results-ad.html?sitepage=searchresults&amp;keyword=' + animal + 
       '" width="160px" height="650px" ' +
       ' marginheight="0px" marginwidth="0px" scrolling="no" frameborder="0" ' +
       ' style="width: 160px; height: 650px; margin: 0px; padding: 0px; border: 0px;"> ' +
       '</iframe>';

      // this takes a while.. do it after releasing the modal loading box
      refreshBreedSuggestions();
      
      // scroll to top of page... are we sure we want to do this?
      window.scroll(0,0);
    },
    failure: function(o) {
      var div = document.getElementById('search_content');
      div.innerHTML = 'Could not fetch Search Results: ' + o.status + ' ' + o.statusText;
      hideLoadingBox();
    }
  });
}

// Facebook Link
function fbs_click_pet_detail(u,t) {pageTracker._trackPageview('outbound/www.facebook.com');window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}

// replaces the skinny search results right rail with the wide pet notes right rail
function showPetnoteRail() {
    document.getElementById("main").className    = "main_300";
    document.getElementById("content").className = "content_300";

    var core = document.getElementById("core");
    core.className = "core_300";
    core.innerHTML = '';
    
    if (document.getElementById('petnote_temp_right_rail')) {
      var rail_contents = document.createElement('div');
      rail_contents.id = 'petnote_rail_contents';
      rail_contents.innerHTML = document.getElementById('petnote_temp_right_rail').innerHTML;
      document.getElementById('petnote_temp_right_rail').innerHTML = '';
      core.appendChild(rail_contents);
    }
}

// replaces any right rail with the skinny search results right rail
function showResultsRail() {
    document.getElementById("main").className    = "main_160";
    document.getElementById("content").className = "content_160";

    var core = document.getElementById("core");
    core.className = "core_160";
    core.innerHTML = '';
    
    if (document.getElementById('results_temp_right_rail')) {
      var rail_contents = document.createElement('div');
      rail_contents.id = 'results_rail_contents';
      rail_contents.innerHTML = document.getElementById('results_temp_right_rail').innerHTML;
      document.getElementById('results_temp_right_rail').innerHTML = '';  
      core.appendChild(rail_contents);
    }
}

function showBannerAd() {
    if (document.getElementById('detail-temp-banner')){
      var ad_contents = document.getElementById('banner_ad');
      ad_contents.innerHTML = document.getElementById('detail-temp-banner').innerHTML;
      document.getElementById('detail-temp-banner').innerHTML = '';
    }
}

// right now, this won't work because google won't let you change ads mid-page.  will need to check with them to fix it.
function showPetnoteAdsense() {
    // write the adsense js to the screen
    var script1 = document.createElement('script');
    script1.src = "http://www.petfinder.com/common/javascript/adsense_2.js";
    var script2 = document.createElement('script');
    script2.innerHTML =  "google_max_num_ads = '4'; \n google_skip = '0'; \n google_targeting = 'site_content'; \n google_ad_channel = 'PF_PetNotes';";
    if (location.href.indexOf("dev.petfinder.com") || location.href.indexOf("test.petfinder.com")) {
        script2.innerHTML += " \n google_adtest = 'on'";
    }
    var script3 = document.createElement('script');
// I'm pretty sure we can't add google ads this way.
//    script3.src="http://pagead2." + "googlesyndication" + ".com/pagead/show_ads.js";

    var adBox = document.getElementById('petnote_adsense_container');
    adBox.appendChild(script1);
    adBox.appendChild(script2);
    adBox.appendChild(script3);
}

function sleep() {
  j = 0;
  for (i = 0; i < 1*1000*1000*100; i++){
    j=i+i;
  }
}

function loadVideo() {
  if (document.getElementById('pet-video-id') && document.getElementById('flashcontent') && document.getElementById('myVersion') ) {
    var pfUrl = 'http://' + window.location.hostname + '/';
    var videoUrl = 'http://www.petfinder.com/';
    var videoId = document.getElementById('pet-video-id') ? document.getElementById('pet-video-id').innerHTML : 0;
    var ranNumber=Math.floor(Math.random()*1000);
    var version = deconcept.SWFObjectUtil.getPlayerVersion();
    document.getElementById('myVersion').innerHTML = "&lt;p>You have Flash player " + version['major'] + "."
      + version['minor'] +"."+ version['rev'] +" installed.&lt;/p>";
    var so = new SWFObject(pfUrl + "common/flash/modifiedPlayer.swf", "Petvideo", "298", "250", "8.0.0", "#FFFFFF");
    so.addParam("quality","high");
    so.addParam("wmode", value="transparent");
    so.addVariable("jpg", pfUrl + "images/adoptablepetvideo/iams-clip.jpg");
    so.addVariable("paramString","video=" + videoId);
    so.addVariable("xmlScript",videoUrl + "playlist");
    so.addVariable("autoplay","false");
    so.addVariable("dummy",ranNumber);
    so.write("flashcontent");
  }
}

function clearAllRefinements() {
    // keep the animal type, breed, and location in the form
}

function getSearchCookie() {
    var oUser = YAHOO.util.Cookie.getSubs('search', cookieProps); 
    var sUserName = oUser.name;
}

function saveSearchCookie(newUrl) {
  var cookieSubs = {
    age:     [],
    sex:     [],
    size:    [],
    other:   [],
    house:   [],
    location:'',
    animal:  '',
    distance:'',
    breed:   [],
    petname: ''
  };

  // location
  var locObj = document.getElementById('pet-location') || document.getElementById('location-input');
  if (locObj && locObj.value) {
    if (locObj.value == defaultLocationText) {
      locObj.value = '';
    }
    else {
      cookieSubs.location = locObj.value;
      // for backwards compatibility, fill in the old "location" cookie
      YAHOO.util.Cookie.set('location', locObj.value, cookieProps);
    }
  }
  
  // animal type
  var animal = document.getElementById("animal_type") || document.getElementById("pet_animal_type");
  if (animal && animal.value) {
    cookieSubs.animal = animal.value;
    var animal_array = ['Animal','Barnyard', 'Bird', 'Cat', 'Dog', 'Horse', 'Pig', 'Rabbbit', 'Reptile', 'Small&Furry'];
    for (i = 0; i < animal_array.length; i++) {
      if (animal.value == animal_array[i]) {
        YAHOO.util.Cookie.set('pet.Animal', i, cookieProps);
        break;
      }
    }
  }
  
  // breed input box
  var breed = document.getElementById("pet_breed");
  if (breed && breed.value) {
    //alert('saving typed pet breed: ' + breed.value);
    cookieSubs.breed.push(breed.value);
  }

  // if the user selected the 'change' form or started a new search, don't save the refinements from the old search
  if (newUrl != 'reset') {
  
    
    // refinements
    // we use "try" because this might fail in IE if there are no items with the class 'dimsearch'
    try {
      var refinements = YAHOO.util.Dom.getElementsByClassName('dimsearch');
      var usedLabels = '';
      for (i in refinements) {
        if ( (typeof(refinements[i]) === 'undefined' ) || (refinements[i].checked === false) ) {
          continue;
        }
    
        var label = 'nolabel';
        if (document.getElementById(refinements[i].id + '-label')) {
          label = document.getElementById(refinements[i].id + '-label').innerHTML;
        }
    
        // cut off the span tag containing the number of pets available, if there is one
        if (label.indexOf(' <') >= 0) {
          label = label.substring(0, label.indexOf(' <'));
        }
        // strip out one or more spaces at the end
        label = label.replace(/\s+$/, '');
    
        var refinement = refinements[i].id.replace('r-', '');
        refinement = refinement.substring(0, refinement.indexOf('-'));
      
        // don't save the same label twice
        if (usedLabels.indexOf(label + ' ') >= 0) {
          continue;
        }
    
        if (refinement == "Age") {
          cookieSubs.age.push(label);
          usedLabels += label + ' ';
        }
        else if (refinement == "Sex") {
          cookieSubs.sex.push(label);
          usedLabels += label + ' ';
        }
        else if (refinement == "Size") {
          cookieSubs.size.push(label);
          usedLabels += label + ' ';
        }
        else if (refinement == "OtherConsiderations") {
          cookieSubs.other.push(label);
          usedLabels += label + ' ';
        }
        else if (refinement == "MyHouseholdHas") {
          cookieSubs.house.push(label);
          usedLabels += label + ' ';
        }
      }
    }
    catch(e) {
    }

    // distance
    var dist = document.getElementById("distance");
    if (dist && dist.options) {
      cookieSubs.distance = dist.options[dist.selectedIndex].text;
    }
  
    // name
    var petname = document.getElementById("pet-name");
    var rpetname = document.getElementById("r-pet-name");
    if (petname && petname.value) {
      cookieSubs.petname = petname.value;
    }
    else if (rpetname && rpetname.checked) {
      cookieSubs.petname = document.getElementById("r-pet-name-label").innerHTML;
    }

    // breeds saved in checkboxes
    // we use "try" because this might fail in IE if there are no items with the class 'pet-breed'
    try {
      var breeds = YAHOO.util.Dom.getElementsByClassName('pet-breed');

      for (i in breeds) {
        if ( (typeof(breeds[i]) === 'undefined' ) || (breeds[i].checked === false) ) {
          continue;
        }
        var label2 = 'nolabel';
        if (document.getElementById(breeds[i].id + '-label')) {
          label2 = document.getElementById(breeds[i].id + '-label').innerHTML;
          cookieSubs.breed.push(label2);
        }
      }
    }
    catch(e) {
    }
  }

  if (newUrl == 'start') {
    newUrl = '/pet-search?pet_animal_type=' + cookieSubs.animal + '&pet_breed=' + cookieSubs.breed + '&location=' + cookieSubs.location;
  }
  else if (newUrl == 'reset') {
    newUrl = '/pet-search?pet_animal_type=' + cookieSubs.animal + '&location=' + cookieSubs.location;
  }
  
  
  var targetUrl = newUrl;
  try {
    targetUrl = newUrl || window.location.href;
  }
  catch(e) {
  }

  YAHOO.util.Cookie.setSubs('search', cookieSubs, cookieProps);
  YAHOO.util.Cookie.set('searchUrl', targetUrl, cookieProps);
}


function clearInvalidLocation() {
  YAHOO.util.Cookie.setSub('search', 'location', '', cookieProps);
  if (document.getElementById('location-input')) {
    document.getElementById('location-input').value = defaultLocationText;
  }
}

function showCriteria(obj, prefix, tolower) {
  var str = '';
  var arr = obj.split(",");
  for(i in arr) {
    if (arr[i].length > 0) {
      if (prefix === '') {
        str += arr[i] + "<br />\n";
      }
      else if (tolower) {
        str += prefix + arr[i].toLowerCase() + "<br />\n";
      }
      else {
        str += prefix + arr[i] + "<br />\n";
      }
    }
  }
  return str;
}

function fillStartForm() {
  var cookieSubs = YAHOO.util.Cookie.getSubs('search', cookieProps);
  var searchUrl  = YAHOO.util.Cookie.get('searchUrl', cookieProps);
  
  if (searchUrl) {
    document.getElementById('saved-search-url').value=searchUrl;
  }
  
  if ( (cookieSubs === null) || (typeof(cookieSubs) === 'undefined') ){
    // no cookie. don't prepopulate!
    //document.getElementById('pet-location').value = defaultLocationText;
    return;
  }
  
  // animal type
  if (cookieSubs.animal && (cookieSubs.animal !== '') ) {
    animalObj = document.getElementById('pet_animal_type');
    for ( i = 0; i < animalObj.length; i++ ) {
//    for (i in animalObj.options) {
//      alert('checking animal option ' + i);
      if (animalObj.options[i] && animalObj.options[i].text && (animalObj.options[i].text == cookieSubs.animal)) {
        animalObj.selectedIndex = i;
        break;
      }
    }
  }
  
  // breed
  if (cookieSubs.breed && (cookieSubs.breed.length > 0) ) {
    var breed_name = cookieSubs.breed;
    if (breed_name.indexOf(',') > 0) {
      breed_name = breed_name.substr(0, breed_name.indexOf(','));
    }
	  
    document.getElementById('pet_breed').value = breed_name;
  }  
  
  // location
  if (cookieSubs.location && (cookieSubs.location !== '') ) {
    if (document.getElementById('pet-location')) {
      document.getElementById('pet-location').value = cookieSubs.location;
    }
  }
  //else {
    //document.getElementById('pet-location').value = defaultLocationText;

  //}
  
  // everything else
  everythingElse = showCriteria(cookieSubs.age, '') + showCriteria(cookieSubs.sex, '') + showCriteria(cookieSubs.size, '') + showCriteria(cookieSubs.other, '') + showCriteria(cookieSubs.house, 'My house has ', 1) + showCriteria(cookieSubs.petname, 'Pets named ');
  if (everythingElse !== '') {
    //document.getElementById('other-criteria-head');
    YAHOO.util.Dom.removeClass('other-criteria-head', 'hide');
    document.getElementById('other-criteria').innerHTML = everythingElse;
  }
}

function clearStartRefinements() {
  // only clear it if there's something to clear, not at the very beginning of the page load.
  if(document.getElementById('saved-search-url').value !== '') {
    document.getElementById('saved-search-url').value='';
    YAHOO.util.Dom.addClass('other-criteria-head','hide');
    document.getElementById('other-criteria').innerHTML = '';
  }
}

function clearStartBreed() {
  document.getElementById('pet_breed').value = '';
}

function submitStartForm() {
  if ((document.getElementById('saved-search-url').value === '') || 
      (document.getElementById('saved-search-url').value.indexOf('pet-search') < 0) ||
      (document.getElementById('saved-search-url').value.indexOf(window.location.hostname) < 0)) {
    if (document.getElementById('pet_animal_type').selectedIndex < 1) {
      alert("Select an animal type.");
      return false;
    }
    else if (document.getElementById('pet-location').value == defaultLocationText) {
      alert("Enter your location - " + defaultLocationText + '.');
      return false;
    }
    saveSearchCookie('start');
    return true;
  }
  else {
    window.location.replace(document.getElementById('saved-search-url').value);
    return false;
  }
}

function searchPetName() {
  var petName = document.getElementById('pet-name').value;
  if (petName && (petName !== '') ) {
    var target = window.location.href;
    if (target.indexOf('/pet-search?') >= 0) {
      target = target.substring(target.indexOf('/pet-search?') + 12);
    }
    if (target.indexOf('#') > 0) {
      target = target.substring(0, target.indexOf('#'));
    }
    
    try {	
      YAHOO.util.History.navigate("pet-search", "results-" +  target + '&pet_name=' + petName);
    }
    catch(e) {
      displayPartialSearchResults(target + '&pet_name=' + petName);    
      //alert("error with history: " + e.description + " ; " +  YAHOO.PF.search.history_init);
    }
  }
  return false;
}

// switch between old and new nav for beta
function toggleSearchNav(type) {
	
  // save the user's choice in a single-session cookie
  YAHOO.util.Cookie.setSub('userPrefs', 'searchType', type, cookieProps);
  
  if (type == 'new') {
    // if they want the new one, show the new left nav bar  
    document.getElementById('left-rail').style.visibility = 'visible';
    document.getElementById('left-rail').style.display = 'block';
    YAHOO.util.Dom.addClass('qs-animal', 'hide-select');     
    YAHOO.util.Dom.addClass('qs-age', 'hide-select');     
    YAHOO.util.Dom.addClass('qs-size', 'hide-select');     
    YAHOO.util.Dom.addClass('qs-gender', 'hide-select');
    fillStartForm();
  }
  else if (location.href.indexOf('pet-search')>=0) {
  //alert("pet-search: " + location.href.indexOf('pet-search') + " redirects to http://" + location.hostname + '/pet-adoption/');
    // if they're in search results, go to pet adoption landing page
    window.location.replace('http://' + location.hostname + '/pet-adoption/');
  }
  else {
    // if they're not in search results, just hide the new left nav bar
    document.getElementById('left-rail').style.visibility = 'hidden';
    document.getElementById('left-rail').style.display = 'none';
    YAHOO.util.Dom.removeClass('qs-animal', 'hide-select');     
    YAHOO.util.Dom.removeClass('qs-age', 'hide-select');     
    YAHOO.util.Dom.removeClass('qs-size', 'hide-select');     
    YAHOO.util.Dom.removeClass('qs-gender', 'hide-select');     
  }
}

function checkSearchNav() {
  var type = YAHOO.util.Cookie.getSub('userPrefs', 'searchType');
  
  // if they want the new one, show the new left nav bar
  if (type == 'new') {
    document.getElementById('left-rail').style.visibility = 'visible';
    document.getElementById('left-rail').style.display = 'block';
    YAHOO.util.Dom.addClass('qs-animal', 'hide-select');     
    YAHOO.util.Dom.addClass('qs-age', 'hide-select');     
    YAHOO.util.Dom.addClass('qs-size', 'hide-select');     
    YAHOO.util.Dom.addClass('qs-gender', 'hide-select');
    fillStartForm();
  }
}

function openPhotoView(petid) {
  var photoUrl = document.masterPhoto.src;
  var expression = /\.(\d+-\d)-/; 
  var index = 1;
  if (expression.exec(photoUrl) ) {
      var id_img = RegExp.lastParen.split('-');
      index = id_img[1];
  }
  window.open('/pet-search?R=' + petid + '&photo_view=' + index,'Photo1','height=660,width=778,left=20,top=100,screenx=200,screeny=100,scrollbars=yes');

}

function submitTypedBreed() {
    var target = YAHOO.util.Cookie.get('searchUrl', cookieProps);
    if (target.indexOf('/pet-search?') >= 0) {
      target = target.substring(target.indexOf('/pet-search?') + 12);
    }
    if (target.indexOf('#') > 0) {
      target = target.substring(0, target.indexOf('#'));
    }
    target = target.replace('&partial=true', '');

    if (document.getElementById('refine-submitted').value == 'yes') {
      return;
    }

    try {	
      YAHOO.util.History.navigate("pet-search", "results-" + target + '&pet_breed=' + document.getElementById('pet_breed').value);
    }
    catch(e) {
      displayPartialSearchResults(target + '&pet_breed=' + document.getElementById('pet_breed').value);    
      //alert("error with history: " + e.description + " ; " +  YAHOO.PF.search.history_init);
    }
}

// if they've already hit an autocomplete, it would have submitted the form automatically...
// we want the form to submit only if they hit enter without choosing an autocomplete.
function checkSearchRefine() {
  if (document.getElementById('refine-submitted').value !== 'yes') {
    setTimeout('submitTypedBreed()', 500);
  }
  return false;
}

function showBreedList2(breedUrl) {
    var animalSelect = document.getElementById('pet_animal_type') || document.getElementById('animal_type');
    
    // TODO: if the animal type has changed, save the new search url

    if ( animalSelect && ( animalSelect.selectedIndex > 0 ) ) {
        if(animalSelect.selectedIndex == 9) {
            breedUrl += 'smallFurry';
        }
        else if (animalSelect.selectedIndex == 1) {
            breedUrl += 'BarnYard';
        }
        else {
            breedUrl += animalSelect.value;
        }
    }
    document.location = breedUrl;
}

function searchHistoryHandler(state) {
  if (state.indexOf('pet-') == 0) {
    //alert("loading pet state: " + state);
    displayPetNote('http://' + window.location.hostname + '/petdetail/' + state.substring(4));
  }
  else if (state.indexOf('results-') == 0) {
    displayPartialSearchResults(state.substring(8));
  }
  else {
    //alert("loading new search state " + state);
  }
}

function displaySearchResults() {
   YAHOO.util.Dom.addClass('search-results-table','unhide');
   YAHOO.util.Dom.addClass('search-results-crumb','unhide');
   YAHOO.util.Dom.addClass('search-results-bottom-crumb','unhide');

   //YAHOO.util.Dom.addClass('search-info', 'unhide');
   YAHOO.util.Dom.addClass('refinements', 'unhide');
   YAHOO.util.Dom.addClass('distance', 'unhide');
   
   loadRecentPets('recentpets-container', 'Recently Viewed Pets');
}

function loadPetAds() {
  var animal = document.getElementById('pet-animal-type').innerHTML;
  var video = document.getElementById('pet-video-id') ? 'video' : '';

  // create the two iframe ad elements and add them to the dom
  if ( document.getElementById('banner_ad') ) {
    document.getElementById('banner_ad').innerHTML = '<iframe src="/banner-ad.html?sitepage=petnotes&keyword=' + animal + 
     ',' + video + '" width="728px" height="90px" ' +
     ' marginheight="0px" marginwidth="0px" scrolling="no" frameborder="0" ' +
     ' style="width: 728px; height: 90px; margin: 0px; padding: 0px; border: 0px;"> ' +
     '</iframe>';
  }

  if ( document.getElementById('ad_bar_ad') ) {
    document.getElementById('ad_bar_ad').innerHTML = '<iframe src="/detail-ad.html?sitepage=petnotes&keyword=' + animal + 
     ',' + video + '" width="300px" height="250px" ' +
     ' marginheight="0px" marginwidth="0px" scrolling="no" frameborder="0" ' +
     ' style="width: 300px; height: 250px; margin: 0px; padding: 0px; border: 0px;"> ' +
     '</iframe>';
  }
  
  updateMorePetsLocation("more_pets_nav");
}

function updateMorePetsLocation(linkId) {
    var location = YAHOO.util.Cookie.getSub('search','location', cookieProps);
    var linkEl = document.getElementById(linkId);
    if (location && linkEl && linkEl.href) {
        var morePetsLink = linkEl.href;
        
        // for IE and FF
        linkEl.href = morePetsLink.replace(/location=(.*)$/,'location=' + location);
        
        // for Safari
        linkEl.setAttribute('href', morePetsLink.replace(/location=(.*)$/,'location=' + location));
    }
}

function onPageLoad() {
  try {
    var initialState = YAHOO.util.History.getBookmarkedState('pet-search') || 'search-results'; 
    if (initialState.indexOf('pet-') == 0) {
      displayPetNote('http://' + window.location.hostname + '/petdetail/' + initialState.substring(4));
    }
    else if ((initialState.indexOf('results-') == 0) && (initialState.indexOf('results-undefined') < 0)){
      displayPartialSearchResults(initialState.substring(8));
    }
    else {
      displaySearchResults();
      var animal = document.getElementById('animal_type').options[document.getElementById('animal_type').selectedIndex].value;
      animal = animal.replace('&', '');
      
      // create the two iframe ad elements and add them to the dom
      document.getElementById('banner_ad').innerHTML = '<iframe src="/banner-ad.html?sitepage=searchresults&amp;keyword=' + animal + 
       '" width="728px" height="90px" ' +
       ' marginheight="0px" marginwidth="0px" scrolling="no" frameborder="0" ' +
       ' style="width: 728px; height: 90px; margin: 0px; padding: 0px; border: 0px;"> ' +
       '</iframe>';

      document.getElementById('ad_bar_ad').innerHTML = '<iframe src="/results-ad.html?sitepage=searchresults&amp;keyword=' + animal + 
       '" width="160px" height="650px" ' +
       ' marginheight="0px" marginwidth="0px" scrolling="no" frameborder="0" ' +
       ' style="width: 160px; height: 650px; margin: 0px; padding: 0px; border: 0px;"> ' +
       '</iframe>';

    }
    YAHOO.util.History.register('pet-search', initialState, searchHistoryHandler); 
    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");  
    YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName('petlink'), 'click', clickPetNote);
    
    
  } 
  catch(e) {
    //alert("trying to load unknown history: " + e.description);
  }
}

// Recent Pets START
function addToRecentPets(petid, petshelter, petstatus, petname) {
  var recentPets = YAHOO.util.Cookie.getSubs('recentPets');
  var newRecentPets = {};
  newRecentPets[0] = petid + '-' + petshelter + '-' + petstatus + '-' + petname;
  var i = 0;
  var j = 1;
  for (i in recentPets) {
    var id = recentPets[i].substring(0, recentPets[i].indexOf('-'));
    if (parseInt(id) != parseInt(petid) ) {
      newRecentPets[j] = recentPets[i];
      j++;
      if (j > 7) {
        break;
      }
    }
  }
  YAHOO.util.Cookie.setSubs('recentPets', newRecentPets, cookieProps);
}

function migrateRecentPets(oldCookie, oldCookieName) {
  var recentPetArray  = oldCookie.split('|');
  if (recentPetArray.length > 0) {
    var newRecentPets = {};
    var i = 0;
        
    // go through the recent pets and add each one to the new cookie
    for (recentPet in recentPetArray) {
      var pet     = recentPetArray[recentPet].split(',');
      var petid   = pet[0];
      var petname = pet[1];
      var shelter = pet[2];
      newRecentPets[i] = petid + '-' + shelter + '-A-' + petname;
      i++;
    }
    
    // save the new cookie
    YAHOO.util.Cookie.setSubs('recentPets', newRecentPets, cookieProps);
    
    // delete the old cookie
    YAHOO.util.Cookie.remove(oldCookieName, cookieProps);
  }
}

function loadRecentPets(containerDivId, h2text) {
	
  // migrate old recent pet cookie, if one exists
  var recentPetString = getCookie('pf_recent_pets');
  if (recentPetString) {
    migrateRecentPets(recentPetString, 'pf_recent_pets');
  }

  var searchType = YAHOO.util.Cookie.getSub('userPrefs', 'searchType');
  var recentPets = YAHOO.util.Cookie.getSubs('recentPets');
    
  var petUrlBase = 'http://' + window.location.hostname + '/pet-search?petid=';
  if (searchType != 'new') {
    petUrlBase = 'http://' + window.location.hostname + '/petnote/displaypet.cgi?petid='
  }

  if (recentPets && ( '0' in recentPets ) ) {
    var containerDiv = document.getElementById(containerDivId);
       
    // remove old recent pets
    while (containerDiv.hasChildNodes()) {
      containerDiv.removeChild(containerDiv.firstChild);
    }
        
    // create the recent pets content box
    var innerDiv = document.createElement('div');
    innerDiv.setAttribute('id','recentpets');
    innerDiv.className = 'content_box';
        
    // create the recent pets h2 & br tag
    var h2 = document.createElement('h2');
    h2.innerHTML=h2text;
    innerDiv.appendChild(h2);

    var photoUrlBase = petPhotoBase1 + 'fotos/';

    // go through the recent pets and add each one to the content box
    for (i in recentPets) {
      var id       = recentPets[i].substring(0, recentPets[i].indexOf('-'));
      var therest  = recentPets[i].substring(recentPets[i].indexOf('-')+1);
      var shelter  = therest.substring(0, therest.indexOf('-'));
      var therest2 = therest.substring(therest.indexOf('-')+1);
      var name     = therest2;
      var status   = 'A';
      if (therest2.indexOf('-') > 0) {
        status = therest2.substring(0, therest2.indexOf('-'));
        name   = therest2.substring(therest2.indexOf('-')+1);
      }
      photoUrlBase = ( ( status == 'A' ) ? petPhotoBase1 : petPhotoBase2 ) + 'fotos/';
            
      // create a div for the pet
      var petDiv  = document.createElement('div');
      petDiv.className = 'recentpet';
            
      // make a linked image of the pet & add it to the pet div
      var petImage  = document.createElement('img');
      var petImageA = document.createElement('a');
      var petImageDiv = document.createElement('div');
      var petA      = document.createElement('a');
      petImage.setAttribute('src', photoUrlBase + shelter + '/' + shelter + '.' + id + '-1-fpm.jpg');
      petImage.setAttribute('alt', escape(name));
      petImageA.setAttribute('href', petUrlBase + id);
      petImageA.appendChild(petImage);
      petImageDiv.appendChild(petImageA);
      petDiv.appendChild(petImageDiv);

      // make a linked pet name and add it to the pet div
      var petP = document.createElement('p');
      petA.setAttribute('href', petUrlBase + id);
      petA.innerHTML=name;
      petP.appendChild(petA);
      petDiv.appendChild(petP);
         
      // add the pet div to the recent pets content box
      innerDiv.appendChild(petDiv);
          
      // make a new line every 4 pets (pets start at 0)
      if ( ((i + 1) % 4) == 0) {
        var rEnd = document.createElement('div');
        rEnd.className = 'recentpetsend';
        rEnd.innerHTML = ' ';
        innerDiv.appendChild(rEnd);
      }
    }
        
    // put the recent pets content box in the DOM, inside the container div
    containerDiv.appendChild(innerDiv);
  }
}

function showRecentPets() {
  loadRecentPets(this.container, this.h2);
}

// Recent Pets END

// breed autocomplete START

function refreshBreedSuggestions() {
    // build a breed data structure to populate autocomplete
    var data = {};
    data.breeds = new Array();
    var suggest = document.getElementById('new-breed-suggestions');    
    if (suggest) {
      for (var opt = 0; opt < suggest.length; opt++) {
        if (suggest.options[opt]) {
          data.breeds.push( { name: suggest.options[opt].text, url: suggest.options[opt].value } );
        }
      }
      YAHOO.PF.search.Data = data;
      YAHOO.PF.search.breedAutoComplete = function() {
        var oDS = new YAHOO.util.LocalDataSource(YAHOO.PF.search.Data.breeds);
        oDS.responseSchema = {fields: ['name', 'url']};
    
        var oAC = new YAHOO.widget.AutoComplete('pet_breed', 'breedContainer', oDS);
        oAC.queryMatchContains = true;
        oAC.minQueryLength = 3;
        oAC.maxResultsDisplayed = 20;
        oAC.autoHighlight = false;       
        //oAC.useIFrame = true;

        var selectHandler = function(sType, aArgs) {
          var i = document.getElementById('pet_breed').value.indexOf(' (');
          if (i > 0) {
              document.getElementById('pet_breed').value = document.getElementById('pet_breed').value.substr(0, i);
          }
          document.getElementById('refine-submitted').value = 'yes';
          var myAC = aArgs[0];
          var elLI = aArgs[1];
          var oData = new String(aArgs[2]);
          var newUrl = oData.split(',');

          // fetch a new data set based on breed selection
          YAHOO.util.History.navigate("pet-search", "results-" + newUrl[1]);
          //displayPartialSearchResults(newUrl[1]);
        };

        if (oAC.itemSelectEvent) {
          oAC.itemSelectEvent.subscribe(selectHandler);
        }
 
        return {
          oDS: oDS,
          oAC: oAC
        };
      }();
    }
}

// breed autocomplete END

// this will just cache the url at the browser level.. if the expires time is set right, it will speed up "next pet" pagination.
function fetchPet(petid) {
  var url = 'http://' + window.location.hostname + '/petdetail/' + petid;
  //alert("fetching next pet id: " + petid);
  
  YAHOO.util.Connect.asyncRequest('GET', url, {
    success: function(fetch_o) {
      var regex = /<div id="petnote-shelterid">(\w\w\d+)<\/div>/;
      var shelterMatch = regex.exec(fetch_o.responseText);
      if (shelterMatch.length > 0) {
        var shelter = shelterMatch[1];
        var photo = document.createElement('img');
        photo.src = 'http://photocache.petfinder.com/fotos/' + shelter + '/' + shelter + '.' + petid + '-1-pn.jpg';
        photo.className = 'hidden-img';        
        document.getElementById('petnote_temp_right_rail').appendChild(photo);
      }
    },
    failure: function(fetch_o) {
    }
  });
}

