var defaultLocationText = 'Zip or City, State/Prov';
var topDefaultLocationText = 'Enter zip code';

// Cookie Library START

function getCookie (name) {
  var dcookie = document.cookie;
  var cname = name + '=';
  var clen = dcookie.length;
  var cbegin = 0;
  while (cbegin < clen) {
    var vbegin = cbegin + cname.length;
      if (dcookie.substring(cbegin, vbegin) == cname) {
        var vend = dcookie.indexOf (';', vbegin);
          if (vend == -1) vend = clen;
          return unescape(dcookie.substring(vbegin, vend));
      }
      cbegin = dcookie.indexOf(' ', cbegin) + 1;
      if (cbegin == 0) break;
  }
  return null;
}

function setCookie (name, value, expires) {
  if (!expires) expires = new Date();
  document.cookie = name + '=' + escape (value) + '; path=/' + '; domain=.petfinder.com' ;
}

function delCookie (name) {
  var expireNow = new Date();
  document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT' +  '; path=/';
}

function clearOnClick (inputId, defaultText) {
  if ( document.getElementById(inputId).value == defaultText ) {
    document.getElementById(inputId).value = '';
  }
}

// properties for all Petfinder cookies using YUI
var expire = new Date();

expire.setTime(expire.getTime()+ 2100 * 60 * 60 * 365);

var cookieProps = { 
  domain:  "petfinder.com",
  expires: expire,
  path: "/"
};

YAHOO.namespace('PF.search');

// Cookie Library END

// Event Calendar START

function createXMLHttpRequest() {
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
  try { return new XMLHttpRequest(); } catch(e) {}
  return null;
}

function loadEventCalendar(divId, listId, num) {
	var loc = YAHOO.util.Cookie.getSub('userPrefs','location');//had to use the getSub('parentCookie','childCookie') method to retrieve the subset of data where the location resides__tdb
	var req = createXMLHttpRequest();
	if(loc == null) {
	loc = '07101';
	}
  req.open('GET', '/svcs/event?limit=' + num + '&postal_code=' + loc + '&output=json', true);
  req.onreadystatechange = function() {

    if (req.readyState != 4)  { return; }
    var obj = eval( '(' + req.responseText + ')' );
    if (obj.events) {
      var div = document.getElementById(divId);
      var html = '';
      for (var i = 0; i < obj.events.length; i++) {
        var evt = obj.events[i];
                
        // build a sentence for the event
        var sentence = '<p><a href="/calendar/displayevent.cgi?event_id=' + evt.event_id + '">' + evt.title + '</a> in ' + evt.locality + ', ' + evt.region;
        if (evt.start_date == evt.end_date) {
          sentence += ' on ' + evt.start_date;
        }
        else {
          sentence += ' from ' + evt.start_date + ' to ' + evt.end_date;
        }
        sentence += ' by ' + evt.organization + '</p>';
        html += sentence;
      }
      document.getElementById(listId).innerHTML = html;
    }
  }
  req.send(null);
}

// Event Calendar END

// Flash support START
/*
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
// Flash support END

function loadFPM() {
  var url = (("https:" == document.location.protocol) ? "https://" : "http://") + window.location.hostname + '/fp/petfeed.cgi?lang=json&callback=fpm_ajax';
  YAHOO.util.Connect.asyncRequest('GET', url, {
    success: function(o) {
      eval( o.responseText );
      // var obj = eval( '(' + next_o.responseText + ')' );
    },
    failure: function(o) {
			alert("fpm failure- " +o.statusText);
    }
  });  

}

// Featured Pet Module (home page) START
function fpm_ajax(pet) {
  var preload_image = new Image(); 
  preload_image.src=pet.i.fpm;

  if(pet.id) { 
    var markup = '<div class="fpm_img" style="width: 80px"><a href="' + pet.u + '" class="adopt_me_image"><img src="' + pet.i.fpm + '" alt="' + pet.b + '" /></a></div>';
    markup += '<div class="adopt_me_text">';
    markup += '<p class="fpm_name">I\'m';
    if(pet.n) {
      markup += ' <a href="' + pet.u + '"><span id="fpm_name" class="fpm_petname" style="white-space: nowrap">';
      markup += pet.n + '</span></a>,';
    }
    markup += '</p><p class="fpm_breed"><span id="fpm_breed" style="white-space: nowrap">a ' + pet.b + ' </span><br /><span class="fpm_location">from</p>';
    markup += '<p><a href="' + pet.sh.u + '"><span id="fpm_group" style="white-space: nowrap">' + pet.sh.n + '</span></a>';
    markup += '</p><p style="white-space: nowrap"><span id="fpm_loc">' + pet.c + ', ' + pet.s2 + '</span></p></div>';
        
    document.getElementById('home_page_fpm').innerHTML = markup;
    if(pet.n) { autoEllipseText('fpm_name', pet.n, 60); }
    autoEllipseText('fpm_group', pet.sh.n, 85);
    autoEllipseText('fpm_breed', 'a ' + pet.b, 85);
    autoEllipseText('fpm_loc', pet.c + ', ' + pet.s2, 85);
  }
  else {
    document.getElementById('home_page_fpm').innerHTML = '<div class="adopt_me_text"><h2>Adopt Me!</h2>';
    document.getElementById('home_page_fpm').innerHTML += '<div class="fpm_img"><a href="' + pet.u + '"><img src="' + pet.i.fpm + '" alt="" /></a></div>';
    document.getElementById('home_page_fpm').innerHTML += '<div class="fpm_text"><p class="fpm_name"><a href="' + pet.u + '"><span class="fpm_petname">';        
    document.getElementById('home_page_fpm').innerHTML += pet.n;
    document.getElementById('home_page_fpm').innerHTML += '</span></a>';
    document.getElementById('home_page_fpm').innerHTML += '</p><p class="fpm_location"><br />We\'re sorry, the Featured Pet is not available at this time</p></div></div>';
  }
}

function fpm(pet) {
  var preload_image = new Image(); 
  preload_image.src=pet.i.fpm;

  if(pet.id) { 
    var markup = '<div class="fpm_img" style="width: 80px"><a href="' + pet.u + '" class="adopt_me_image"><img src="' + pet.i.fpm + '" alt="' + pet.b + '" /></a></div>';
    markup += '<div class="adopt_me_text">';
    markup += '<p class="fpm_name">I\'m';
    if(pet.n) {
      markup += ' <a href="' + pet.u + '"><span id="fpm_name" class="fpm_petname" style="white-space: nowrap">';
      markup += pet.n + '</span></a>,';
    }
    markup += '</p><p class="fpm_breed"><span id="fpm_breed" style="white-space: nowrap">a ' + pet.b + ' </span><br /><span class="fpm_location">from</p>';
    markup += '<p><a href="' + pet.sh.u + '"><span id="fpm_group" style="white-space: nowrap">' + pet.sh.n + '</span></a>';
    markup += '</p><p style="white-space: nowrap"><span id="fpm_loc">' + pet.c + ', ' + pet.s2 + '</span></p></div>';
        
    document.write(markup);
    if(pet.n) { autoEllipseText('fpm_name', pet.n, 60); }
    autoEllipseText('fpm_group', pet.sh.n, 85);
    autoEllipseText('fpm_breed', 'a ' + pet.b, 85);
    autoEllipseText('fpm_loc', pet.c + ', ' + pet.s2, 85);
  }
  else {
    document.write('<div class="adopt_me_text"><h2>Adopt Me!</h2>'); 
    document.write('<div class="fpm_img"><a href="' + pet.u + '"><img src="' + pet.i.fpm + '" alt="" /></a></div>');
    document.write('<div class="fpm_text"><p class="fpm_name"><a href="' + pet.u + '"><span class="fpm_petname">');        
    document.write(pet.n);
    document.write('</span></a>');
    document.write('</p><p class="fpm_location"><br />We\'re sorry, the Featured Pet is not available at this time</p></div></div>');
  }
}
// Featured Pet Module (home page) END

// Find Animal Rescue Groups in the right rail START

function setAwoForm() {
  var awoForm = document.getElementById('awoForm');
  var cookieSubs = YAHOO.util.Cookie.getSubs('userPrefs', cookieProps);
  if (awoForm) {
    awoForm.keyword.value = 'Any';
    if( (!cookieSubs) || ( cookieSubs.awoLocation == null) ) {
      awoForm.location.value = 'Zip or City, State/Prov';
    }
    else {
      awoForm.location.value = cookieSubs.awoLocation;
    }
  }
}

function clearAwoLocation() {
  var awoForm = document.getElementById('awoForm');

  if(awoForm.location.value == 'Zip or City, State/Prov') {
    awoForm.location.value = '';
  }
}

function clearAwoKeyword() {
  var awoForm = document.getElementById('awoForm');

  if(awoForm.keyword.value == 'Any') {
    awoForm.keyword.value = '';
  }
}

//Any is the default value for the keyword field
//we need to reset it if the user has not typed in a keyword
function submitAwoSearch() {
    var awoForm = document.getElementById('awoForm');

    if(awoForm.keyword.value == 'Any') {
        awoForm.keyword.value = '';
    }
    return set_awo_user_pref_cookie();
}

// The following is a hack to allow us to call setAwoForm on
// page load - more or less - without having to resort to window.onload

if ( document.addEventListener ) {
  document.addEventListener( 'DOMContentLoaded', setAwoForm, false );
}
else if ( document.all && ! window.opera ) {
  document.write('<script type="text/javascript" id="setAwoForm" ' + 'defer="defer" src="javascript:void(0)"></script>');
  var contentLoader = document.getElementById('setAwoForm');
  contentLoader.onreadystatechange = function () {
    if ( this.readyState == 'complete' ) setAwoForm();
  };
}

// Find Animal Rescue Groups in the right rail START

// Suckerfish drop-down menu START
function sfHover() {
  if (document.getElementById('menu_bar_nav')) {
    var sfEls = document.getElementById('menu_bar_nav').getElementsByTagName('li');
    if (sfEls) {
      for ( var i = 0; i < sfEls.length; i++ ) {
        // Must special-case the first element in the list to fix an IE bug !!
        if (sfEls[i] == document.getElementById('item_a')) {
          sfEls[i].onmouseover = function () {
            this.className += ' sfhover';
            if (document.getElementById('qs-animal')) {
              document.getElementById('qs-animal').style.visibility = 'hidden';
            }
	    if (document.getElementById('pet_animal_type')) {
              document.getElementById('pet_animal_type').style.visibility = 'hidden';
	    }
          }
          sfEls[i].onmouseout = function () {
            this.className = this.className.replace( 'sfhover', '' );
            if (document.getElementById('qs-animal')) {
              document.getElementById('qs-animal').style.visibility = 'visible';
            }
	    if (document.getElementById('pet_animal_type')) {
              document.getElementById('pet_animal_type').style.visibility = 'visible';
	    }
          }
        }
        else if ((sfEls[i] == document.getElementById('item_c')) 
          && (document.getElementsByName('classifiedSearch') != null)
          && (document.getElementById('state') != null)
          && (document.getElementById('order') != null)) {
            sfEls[i].onmouseover = function () {
              this.className += ' sfhover';
              document.getElementById("state").style.visibility = 'hidden';
              document.getElementById("order").style.visibility = 'hidden';
            }
            sfEls[i].onmouseout = function () {
              this.className = this.className.replace( 'sfhover', '' );
              document.getElementById("state").style.visibility = 'visible';
              document.getElementById("order").style.visibility = 'visible';
            }
        }
        else if ((sfEls[i] == document.getElementById('item_h'))
          || (sfEls[i] == document.getElementById('item_i'))) {
            void(0);
        }
        else {
          sfEls[i].onmouseover = function () {
            this.className += ' sfhover';
          }
          sfEls[i].onmouseout = function () {
            this.className = this.className.replace( 'sfhover', '' );
          }
        }
      }
    }
  }
}

if ( document.all && ! window.opera ) {
  document.write('<script type="text/javascript" id="suckerfishLoader" ' + 'defer="defer" src="javascript:void(0)"><\/script>');
  var contentLoader = document.getElementById('suckerfishLoader');
    contentLoader.onreadystatechange = function () {
      if ( this.readyState == 'complete' ) sfHover();
  };
}

// Suckerfish drop-down menu END

// Left-side search pre-population START

function showBreedList(breedUrl) {
  var search = document.getElementById('search');

  if(search.elements[1].selectedIndex > 0) {
    setCookie('pet.Animal',search.elements[1].selectedIndex,exp);
    if(search.elements[1].selectedIndex == 9) {
      breedUrl += 'smallFurry';
    }
    else {
      breedUrl += search.elements[1].value;
    }
  }
  document.location = breedUrl;
}

function clearSearchLocation() {
  var location = document.getElementById('pet-location');

  if( location && ( location.value == defaultLocationText) ) {
    location.value = "";
  }
}

function topClearSearchLocation() {
  var location = document.getElementById('top-pet-location');

  if( location && ( location.value == topDefaultLocationText) ) {
    location.value = "";
  }
}

function getSelectValue (element) {
  if (element && element.name) {
    var value = getCookie(element.name);
      if (value != null && value != '') element.selectedIndex = value;
  }
}

function setSearchForm() {
  var search = document.getElementById('search');
  if (search && search.location) {
    var locValue = getCookie('location');
    var animals = document.getElementById('qs-animal');
    var breed = document.getElementById('qs-breed');
    var size = document.getElementById('qs-size');
    var age = document.getElementById('qs-age');
    var gender = document.getElementById('qs-gender');

    if(locValue == null) {
      search.location.value = 'Zip or City, State/Prov';
    }
    else {
      search.location.value = locValue;
      if ( document.searchad ) document.searchad.location.value = locValue;
    }
    getSelectValue(animals);
    getValue(breed);
    getSelectValue(size);
    getSelectValue(age);
    getSelectValue(gender);
  }
}

function getValue (element) {
  if (element && element.name) {
    var value=getCookie(element.name);
    if (value != null) element.value=value;
  }
}

// The following is a hack to allow us to call setSearchForm on
// page load (more or less) without having to resort to window.onload
if ( document.addEventListener ) {
  document.addEventListener( 'DOMContentLoaded', setSearchForm, false );
}
else if ( document.all && ! window.opera ) {
  document.write('<script type="text/javascript" id="setSearchForm" ' + 'defer="defer" src="javascript:void(0)"></script>');
  var contentLoader = document.getElementById('setSearchForm');
  contentLoader.onreadystatechange = function () {
    if ( this.readyState == 'complete' ) setSearchForm();
  };
}
// Left-side search pre-population END

// Auto Ellipse support START
function autoEllipseText( element, text, width ) {
  inSpan = document.getElementById(element);
  if( inSpan && ( inSpan.offsetWidth > width ) ) {
    var i = 1;
    inSpan.innerHTML = ' ';
    while( ( inSpan.offsetWidth < width ) && ( i < text.length ) ) {
      inSpan.innerHTML = text.substr( 0, i ) + '...';
      i++;
    }
    inSpan.title = text;
  }
}

function autoEllipseLibraryBreadcrumb( searchCrumbText, bookCrumbText, titleCrumbText, topicId ) {
  var width = 100;
  if (topicId === 'how-to-help-pets') {
    width=70;
  }
  else if (topicId === 'your-pet-and-you') {
    width=90;
  }
  else if (topicId === 'pet-training') {
    width=115;
  }
  else if (topicId === 'pet-health') {
    width=110;	     
  }
  else if (topicId === 'pet-care') {
    width=115;
  }
  else if (topicId === 'before-pet-adoption') {
    width=90;
  }
  autoEllipseText( 'search-crumb', searchCrumbText, width );
  autoEllipseText( 'book-crumb',   bookCrumbText,   width );
  autoEllipseText( 'title-crumb',  titleCrumbText,  width );
}
// Auto ellipse support END

// Facebook Connect START
function facebook_not_connected(){
  FB.XFBML.Host.parseDomTree();
}

function facebook_connected()  {    
  // in XFBML, tell Facebook to re-process the document 
  FB.XFBML.Host.parseDomTree();
}

// fbs_click_pet_detail is a function to use in the Facebook Link for Share on Facebook on pet notes page
function facebook_share(u,t) {
  _gaq.push(['_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;
}
// Facebook Connect END

// Happy Tails START
function browse_by_month(baseUrl, by_month){
  var my = document.getElementById(by_month).value.split('-');
  window.location = baseUrl + '?month=' + my[0] + '&amp;year=' + my[1];
}

function init_quick_search(inputId, defaultText) {
  if ( document.getElementById(inputId).value == defaultText ) {
    document.getElementById(inputId).value = '';
  }
}
// Happy Tails END

// Search tabular hover START

// This is an unfortunate hack to make interactive table row hover style
// changes work in IE 6. On page load - more or less, we walk the DOM looking
// for tables that have the style "interactive" in them. If we find it,
// we take each row and add an onmouseover and onmouseout events to
// toggle the row's style - which we can then touch with CSS.
function tabularHoverInit() {
  if ( ( !document.all ) || parseInt( navigator.appVersion.substr( navigator.appVersion.indexOf('MSIE') + 5, 1 ) ) > 6) return;

  var tables = document.getElementsByTagName('table');
  for ( var t = 0; t < tables.length; t++ ) {
    if ( tables[t].className.indexOf('interactive') != -1 ) {
      var rows = document.getElementsByTagName('tr');
      for ( var i = 0; i < rows.length; i++ ) {
        rows[i].onmouseover = function() {
          this.className += ' hover';
        };
        rows[i].onmouseout = function() {
          this.className = this.className.replace( 'hover', '' );
        };
      }
    }
  }
}

// The following is a hack to allow us to call tabularHoverInit on
// page load - more or less - without having to resort to window.onload
if ( document.addEventListener ) {
  document.addEventListener( 'DOMContentLoaded', tabularHoverInit, false );
}
else if ( document.all && ! window.opera ) {
  document.write('<script type="text/javascript" id="tabularHoverInitLoader" ' + 'defer="defer" src="javascript:void(0)"></script>');
  var contentLoader = document.getElementById('tabularHoverInitLoader');
  contentLoader.onreadystatechange = function () {
    if ( this.readyState == 'complete' ) tabularHoverInit();
  };
}
// Search tabular hover END

// Pet Search results stuff START

/* not likely used by anything, tsc 2010-04-01
function petNoteJs(peturl, petid) {
  document.petNote.petid.value=petid;
  var actionString = peturl + '/petdetail/' + petid;
  if(document.petNote.tmpl && document.petNote.tmpl.value === 'vbpn') {
    actionString = actionString + '&tmpl=vbpn';
    if(document.petNote.canada && document.petNote.canada.value) {
      actionString = actionString + '&canada=1';
    }
  }
  document.petNote.action = actionString;
  document.petNote.submit();
}
*/

// Pet Search results stuff END

// Pet Notes stuff START
function sponsorMe(petId) {
  var url = 'https://resources.petfinder.com/sap/sponsorme.cgi?pet_id=' + petId;
  window.open(url,'donatewin','width=700,height=800,left=0,top=0,resizable=yes,scrollbars=yes,toolbar=no');
  return false;
}

function openPhotoView(petid) {
  var photoUrl = document.masterPhoto.src;
  var expression = /\.(\d+-\d)-/; 
  var index = 1;
  // figure out which image is being displayed in the big photo window
  if (expression.exec(photoUrl) ) {
    var id_img = RegExp.lastParen.split('-');
    index = id_img[1];
  }
  // open the enlarge photo popup, with the focus on "index"
  var photowin = window.open('/petdetail/' + petid + '?photo_view=' + index,'Photo1','height=7000,width=900,left=20,top=100,screenx=200,screeny=100,scrollbars=yes');
  // this will bring the popup to the front if it was previously left open
  photowin.focus();
}

function hideBox(id) {
  box=document.getElementById(id); 
  if (box) {
    box.style.visibility='hidden'; 
    box.style.display='none'; 
    box.style.position='absolute';
  }
}

function showBox(id) {
  box=document.getElementById(id);

  box.style.display="none";
  var redrawFix = box.offsetHeight;

  box.style.visibility='visible';
  box.style.display='inline';
  box.style.position='relative'; 
	
}

function showVideoBox(id) {
  box=document.getElementById(id);
  if (box) {
    box.style.display="none";
    var redrawFix = box.offsetHeight;

    box.style.visibility='visible';
    box.style.display='inline';
    box.style.position='relative';
  }
}

function showEmbeddedVideoBox(id) {
  box=document.getElementById(id);
  if (box) {
    box.style.display="none";
    var redrawFix = box.offsetHeight;

    box.style.visibility='visible';
    box.style.display='block';
    box.style.position='absolute';		
  }
}


// toggles the media box in petnotes
// photo_url can be video or a url to a preview photo
function mediaToggle(video_box_id, photo_box_id, photo_url) {
  if (photo_url === 'video') {
    if (video_box_id == 'embedded-video') {
      showEmbeddedVideoBox(video_box_id);
    }
    else {
      showVideoBox(video_box_id);
    }
    hideBox(photo_box_id);
  } 
  else {
    document.masterPhoto.src = photo_url;
    showBox(photo_box_id);
    hideBox(video_box_id);
  }
}

function togglePetDescription(moreless) {
  if (moreless == 'more') {
    document.getElementById('pf-pet-description-snippet').style.visibility = 'hidden';
    document.getElementById('pf-pet-description-snippet').style.display = 'none';
    document.getElementById('pf-pet-description-snippet').style.position= 'absolute';
    document.getElementById('read-more').style.visibility               = 'hidden';
    document.getElementById('read-more').style.display               = 'none';
    document.getElementById('read-more').style.position              = 'absolute';
    document.getElementById('pf-pet-description-all').style.visibility     = 'visible';
    document.getElementById('pf-pet-description-all').style.display     = 'inline';
    document.getElementById('pf-pet-description-all').style.position    = 'static';
    document.getElementById('read-less').style.visibility               = 'visible';
    document.getElementById('read-less').style.display               = 'block';
    document.getElementById('read-less').style.position              = 'static';
    //_gaq.push(['_trackPageview', 'petdetail/readmore']);
    //DIT.oasc.refresh();
  }
  else {
    document.getElementById('pf-pet-description-snippet').style.visibility = 'visible';
    document.getElementById('pf-pet-description-snippet').style.display = 'inline';
    document.getElementById('pf-pet-description-snippet').style.position= 'static';
    document.getElementById('read-more').style.visibility               = 'visible';
    document.getElementById('read-more').style.display               = 'block';
    document.getElementById('read-more').style.position              = 'static';
    document.getElementById('pf-pet-description-all').style.visibility     = 'hidden';
    document.getElementById('pf-pet-description-all').style.display     = 'none';
    document.getElementById('pf-pet-description-all').style.position    = 'absolute';
    document.getElementById('read-less').style.visibility               = 'hidden';
    document.getElementById('read-less').style.display               = 'none';
    document.getElementById('read-less').style.position              = 'absolute';
    //window.frames['iframe-ad-container-TopLeft'].location.reload();//reload the top ad
    //window.frames['iframe-ad-container-x17'].location.reload();//reload the right rail ad
    //window.frames['iframe-ad-container-x25'].location.reload();//reload the 2nd right rail ad
    //DIT.oasc.refresh();
    //_gaq.push(['_trackPageview', 'petdetail/readmore']);
  }
}
// Pet Notes stuff END

// used in new search form
function getSelectedValues(id) {
  var str = new String();
  for(var i = 0; i < id.options.length; i++) {
    if(id.options[i].selected) {
      str += str.length > 0 ? ',' + id.options[i].value : id.options[i].value;
    }
  }
  return str.length > 0 ? str : null;
}

// used in Pet First sponsor boxes
function openPetFirstQuote(name, animal, age, breed, gender, utm_medium) {
  var url = 'https://pets.petfirsthealthcare.com/petfinder/quote.aspx?pet_name=' + name + '&pet_species=' + animal + '&pet_age=' + age + '&pet_breed=' + breed + '&pet_gender=' + gender + '&utm_source=petfinder&utm_campaign=pfsponsor&utm_medium=' + utm_medium;
  var petfirstwin = window.open(url, 'petfirstwin', 'width=330,height=450,left=0,top=0,resizable=yes,scrollbars=yes,toolbar=no');
  petfirstwin.focus();
  _gaq.push(['_trackPageview', 'sponsors/petfirst']);
  return false;
}

function featuredPetsByBreed(animal, breed, photoBase) {
  var url = 'http://' + window.location.hostname + '/common/ajax/featured-pets.cgi?pet_animal_type=' + animal + '&pet_breed=' + breed;
  if (getCookie('location')) {
    url += '&location=' + getCookie('location');
  }

  YAHOO.util.Connect.asyncRequest('GET', url, {
    success: function(next_o) {
      var obj = eval( '(' + next_o.responseText + ')' );
      if (obj.pets) {
        var innerHTML = '';
        for(p in obj.pets) {
          pet = obj.pets[p];
          innerHTML += '<li><div class="photo"><a href="/petdetail/' + pet.identifier + '"><img style="width: 100px" alt="' + breed + ' Cat: ' + pet.name + '" src="' + pet.image + '" /></a>' + '</div><a href="/petdetail/' + pet.identifier + '">' + pet.name + '</a><br/>' + pet.city + ', ' + pet.state + '</li>';
        }
        document.getElementById('featured-pet-list').innerHTML = innerHTML;
      }
    },
    failure: function(o) {
    }
  });  
}

function showVideoArrow(id) {
  var agt=navigator.userAgent.toLowerCase();
  if ( document.getElementById(id) && document.getElementById(id + '-img') && (agt.indexOf("msie 6.0") == -1)) {
    document.getElementById(id).style.visibility="visible";
    document.getElementById(id + '-img').style.visibility="visible";
  }
}

function hideVideoArrow(id) {
  var agt=navigator.userAgent.toLowerCase();
  if ( document.getElementById(id) && document.getElementById(id + '-img') && (agt.indexOf("msie 6.0") == -1)) {
    document.getElementById(id).style.visibility="hidden";
    document.getElementById(id + '-img').style.visibility="hidden";
  }
}

// XXX for backwards compatibility during migration.  remove this one release
// cycle after migrating AWO search to endeca
function set_user_pref_cookie() {
  return set_pet_user_pref_cookie();
}

function set_pet_user_pref_cookie() {
// set up object for combined cookie, retaining old data from userPrefs if present
  var cookieSubs = YAHOO.util.Cookie.getSubs('userPrefs');
  if (!cookieSubs) {
    cookieSubs = {
      location:    '',
      animal:      '',
      breed:       '',
      awoLocation: ''
    };
  }
  // if they're in the new search, give them the new search cookie 
  // so they don't accidentally get back to the old search
  cookieSubs.searchType = 'new';
  // location - don't save if it contains the default text 'Zip or city....'
  var locObj = document.getElementById('pet-location') || document.getElementById('qs-location');
  if (locObj && locObj.value && (locObj.value != defaultLocationText) ) {
    cookieSubs.location = locObj.value;
  }
  // allow the user to delete the saved location
  else if (locObject && (locObject.value == '')) {
    cookieSubs.location = '';
  }
  // AWO location - don't save if it contains the default text 'Zip or city....'
  var awoLocObj = document.getElementById('fg-location');
  if (awoLocObj && awoLocObj.value
    && (awoLocObj.value != defaultLocationText) ) {
      cookieSubs.awoLocation = awoLocObj.value;
  }
  // allow the user to delete the saved location
  else if (awoLocObj && (awoLocObj.value == '')) {
    cookieSubs.awoLocation = '';
  }
  // animal type
  var animal = document.getElementById("pet_animal_type");
  if (animal.value.length > 0 ) {
    cookieSubs.animal = animal.value;
  }
  // allow the user to delete the saved animal
  else if (animal) {
    cookieSubs.animal = '';
  }
  // breed input box
  var breed = document.getElementById("pet_breed");
  if (breed && breed.value) {
    cookieSubs.breed = breed.value;
  }
  // allow the user to delete the saved breed
  else if (breed) {
    cookieSubs.breed = '';
  }
  // save the combined cookie
  YAHOO.util.Cookie.setSubs('userPrefs', cookieSubs, cookieProps);
  return true;
}

function top_set_pet_user_pref_cookie() {
// set up object for combined cookie, retaining old data from userPrefs if present
  var cookieSubs = YAHOO.util.Cookie.getSubs('userPrefs');
  if (!cookieSubs) {
    cookieSubs = {
      location:    '',
      animal:      '',
      breed:       '',
      awoLocation: ''
    };
  }
  // if they're in the new search, give them the new search cookie 
  // so they don't accidentally get back to the old search
  cookieSubs.searchType = 'new';
  // location - don't save if it contains the default text 'Zip or city....'
  var locObj = document.getElementById('top-pet-location');
  if (locObj && locObj.value && (locObj.value != topDefaultLocationText) ) {
    cookieSubs.location = locObj.value;
  }
  else if (locObj) {
    // highlight box if no location has been entered.
    locObj.style.border = '2px solid #fe6930';
    return false;
  }
  else {
    alert('Please enter your location.');	  
    return false;
  }
  // allow the user to delete the saved location
  //else if (locObj && (locObj.value == '')) {
  //  cookieSubs.location = '';
  //}
  
  // AWO location - don't save if it contains the default text 'Zip or city....'
  var awoLocObj = document.getElementById('fg-location');
  if (awoLocObj && awoLocObj.value
    && (awoLocObj.value != defaultLocationText) ) {
      cookieSubs.awoLocation = awoLocObj.value;
  }
  // allow the user to delete the saved location
  else if (awoLocObj && (awoLocObj.value == '')) {
    cookieSubs.awoLocation = '';
  }
  // animal type
  var animal = document.getElementById("top-pet_animal_type");
  if (animal.value.length > 0 ) {
    cookieSubs.animal = animal.value;
  }
  // allow the user to delete the saved animal
  else if (animal) {
    cookieSubs.animal = '';
  }
  // breed input box
  var breed = document.getElementById("top-pet_breed");
  if (breed && breed.value) {
    cookieSubs.breed = breed.value;
  }
  // allow the user to delete the saved breed
  else if (breed) {
    cookieSubs.breed = '';
  }
  // save the combined cookie
  YAHOO.util.Cookie.setSubs('userPrefs', cookieSubs, cookieProps);
  return true;
}

function set_awo_user_pref_cookie() {
// set up object for combined cookie, retaining old data from userPrefs if present
  var cookieSubs = YAHOO.util.Cookie.getSubs('userPrefs');
  if (!cookieSubs) {
    cookieSubs = {
      location:    '',
      animal:      '',
      breed:       '',
      awoLocation: ''
    };
  }
  // if they're in the new search, give them the new search cookie 
  // so they don't accidentally get back to the old search
  cookieSubs.searchType = 'new';
  // AWO location - don't save if it contains the default text 'Zip or city....'
  var awoLocObj = document.getElementById('fg-location');
  if (awoLocObj && awoLocObj.value
    && (awoLocObj.value != defaultLocationText) ) {
      cookieSubs.awoLocation = awoLocObj.value;
  }
  // allow the user to delete the saved location
  else if (awoLocObject && (awoLocObject.value == '')) {
    cookieSubs.awoLocation = '';
  }
  // save the combined cookie
  YAHOO.util.Cookie.setSubs('userPrefs', cookieSubs, cookieProps);
  return true;
}

// upon submission of the search by pet name form.
function searchPetName() {
  var petName = document.getElementById('pet-name').value;
  if (petName && (petName !== '') ) {
    // append the pet name to the current page's url to add the refinement
    window.location.href = window.location.href + '&name=' + petName;
  }
  return false;
}

/* Recent Pets START */

// adds a pet to the recent pets cookie

/*
function addToRecentPets(petid, petshelter, petstatus, petname) {
  var recentPets = YAHOO.util.Cookie.getSubs('recentPets');
  var newRecentPets = {};
  
  // add the new pet to the front of the array
  newRecentPets[0] = petid + '-' + petshelter + '-' + petstatus + '-' + petname;
  
  // add old recent pets to the array - up to 7, skipping the current pet if present
  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;
      }
    }
  }
  
  // save the cookie
  YAHOO.util.Cookie.setSubs('recentPets', newRecentPets, cookieProps);
}

// retrieve the recent pets list from the cookie and display
function loadRecentPets(containerDivId, h2text) {

  // retrieve cookie information
  var searchType = YAHOO.util.Cookie.getSub('userPrefs', 'searchType');
  var recentPets = YAHOO.util.Cookie.getSubs('recentPets');
    
  // use a different pet URL - based on whether they're using the old or new search
  var petUrlBase = 'http://www.petfinder.com/petdetail/';

  // if there are recent pets, display recent pets box
  if (recentPets && ( '0' in recentPets ) ) {
    var containerDiv = document.getElementById(containerDivId);
       
    // empty out the container div, just in case
    containerDiv.innerHTML = '';
        
    // 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 + '?rvp=1');
      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 + '?rvp=1');
      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);
  }
}
*/

/* Recent Pets END */

// clear the start breed
function clearStartBreed() {
  document.getElementById('pet_breed').value = '';
}

// clear the start breed
function topClearStartBreed() {
  document.getElementById('top-pet_breed').value = '';
}

function fillStartForm() {
  var cookieSubs = YAHOO.util.Cookie.getSubs('userPrefs', cookieProps);
  
  if ( (cookieSubs === null) || (typeof(cookieSubs) === 'undefined') ){
    // no cookie. don't prepopulate!
    return;
  }
  
  // animal type
  if (cookieSubs.animal && (cookieSubs.animal !== '') && document.getElementById('pet_animal_type') ) {
    var animalObj = document.getElementById('pet_animal_type');
    for ( var i = 0; i < animalObj.length; i++ ) {
      if (animalObj.options[i] && animalObj.options[i].value && (animalObj.options[i].value == cookieSubs.animal)) {
        animalObj.selectedIndex = i;
        break;
      }
    }
  }
  
  // breed
  if (cookieSubs.breed && (cookieSubs.breed.length > 0) && document.getElementById('pet_breed')) {
    document.getElementById('pet_breed').value = cookieSubs.breed;
  }  
  
  // location
  var location = document.getElementById('pet-location') || document.getElementById('qs-location');
  if (cookieSubs.location && (cookieSubs.location !== '') && location ) {
      location.value = cookieSubs.location;
  }
}

function topFillStartForm() {
  var cookieSubs = YAHOO.util.Cookie.getSubs('userPrefs', cookieProps);
  
  if ( (cookieSubs === null) || (typeof(cookieSubs) === 'undefined') ){
    // no cookie. don't prepopulate!
    return;
  }
  
  // top animal type
  if (cookieSubs.animal && (cookieSubs.animal !== '') && document.getElementById('top-pet_animal_type') ) {
    var animalObj = document.getElementById('top-pet_animal_type');
    for ( var i = 0; i < animalObj.length; i++ ) {
      if (animalObj.options[i] && animalObj.options[i].value && (animalObj.options[i].value == cookieSubs.animal)) {
        animalObj.selectedIndex = i;
        break;
      }
    }
  }
  
  // top breed
  if (cookieSubs.breed && (cookieSubs.breed.length > 0) && document.getElementById('top-pet_breed')) {
    document.getElementById('top-pet_breed').value = cookieSubs.breed;
  }  
  
  // top location
  var top_location = document.getElementById('top-pet-location');
  if (cookieSubs.location && (cookieSubs.location !== '') && top_location ) {
      top_location.value = cookieSubs.location;
  }
}


/* START ajax pet count updater */
function updatePetCount() {
  var url = 'http://' + window.location.hostname + '/common/ajax/pet-count.cgi';
  var pet_span     = document.getElementById('welcome-pet-total');
  var shelter_span = document.getElementById('welcome-shelter-total');
  
  // only call the ajax updater if the page needs it (not all pages do)
  if ( pet_span || shelter_span ) {
    YAHOO.util.Connect.asyncRequest('GET', url, {
      success: function(next_o) {
        var obj          = eval( '(' + next_o.responseText + ')' );
        var pet_span     = document.getElementById('welcome-pet-total');
        var shelter_span = document.getElementById('welcome-shelter-total');
        if ( (obj.pet_total) && (pet_span) ) {
          pet_span.innerHTML = obj.pet_total;
        }
        if ( (obj.shelter_total) && (shelter_span) ) {
          shelter_span.innerHTML = obj.shelter_total;
        }
      },
      failure: function(o) {
      }
    });  
  }
}

// set up the ajax pet count update function to load when the page loads
if ( document.addEventListener ) {
  document.addEventListener( 'DOMContentLoaded', updatePetCount, false );
}
else if ( document.all && ! window.opera ) {
  document.write('<script type="text/javascript" id="updatePetCountLoader" ' + 'defer="defer" src="javascript:void(0)"></script>');
  var contentLoader = document.getElementById('updatePetCountLoader');
  contentLoader.onreadystatechange = function () {
    if ( this.readyState == 'complete' ) updatePetCount();
  };
}
/* END ajax pet count updater */


