var defaultLocationText = 'Zip or City, State/Prov';

// 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 = '';
    }
}

function petnote (id, currentPage, pageOffset){
	query =    currentPage + '|' + 'offset=' + pageOffset;
	setCookie('searchQuery',query);
        window.location="/petdetail/"+id;
}	

// 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) {}
   //alert("XMLHttpRequest not supported");
   return null;
}

function loadEventCalendar(divId, listId, num) {
    var loc = getCookie('location');
    var req = createXMLHttpRequest();
    req.open('GET', '/common/ajax/local-events.cgi?num=' + num + '&loc=' + loc, 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="http://www.petfinder.com/calendar/displayevent.cgi?id=' + evt.id + '">' + 
                    evt.title + '</a> in ' + evt.city + ', ' + evt.state;
                if (evt.startdate == evt.enddate) {
                    sentence += ' on ' + evt.startdate;
                }
                else {
                    sentence += ' from ' + evt.startdate + ' to ' + evt.enddate;
                }
                sentence += ' by ' + evt.organization + '</p>';
                html += sentence;
            }
            document.getElementById(listId).innerHTML = html;
            //div.style.visibility  = 'visible';
            //div.style.position    = 'static';
        }
    }
    req.send(null);
}

// Event Calendar END

// OAS ad serving stuff START
/*
OAS_url = 'http://oascentral.discovery.com/RealMedia/ads/';
OAS_target = '_top';
OAS_rn = '001234567890'; OAS_rns = '1234567890';
OAS_rn = new String (Math.random()); OAS_rns = OAS_rn.substring (2, 11);

function OAS_NORMAL(pos) {
    document.write('<A HREF="' + OAS_url + 'click_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@'
        + OAS_listpos + '!' + pos + '?' + OAS_query + '" TARGET=' + OAS_target + '>');
    document.write('<IMG SRC="' + OAS_url + 'adstream_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' 
        + OAS_listpos + '!' + pos + '?' + OAS_query + '" BORDER=0></A>');
}

function OAS_AD(pos) {
    OAS_NORMAL(pos);
}

document.write('');
*/
/*
//configuration
OAS_url = 'http://oascentral.discovery.com/RealMedia/ads/';
//OAS_sitepage = window.location.hostname + window.location.pathname;
OAS_target = '_top';
//end of configuration
OAS_version = 10;
OAS_rn = '001234567890'; OAS_rns = '1234567890';
OAS_rn = new String (Math.random()); OAS_rns = OAS_rn.substring (2, 11);
function OAS_NORMAL(pos) {
document.write('<A HREF="' + OAS_url + 'click_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@'
+ OAS_listpos + '!' + pos + '?' + OAS_query + '" TARGET=' + OAS_target + '>');

document.write('<IMG SRC="' + OAS_url + 'adstream_nx.ads/' + OAS_sitepage + '/1' + OAS_rns +
'@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" BORDER=0></A>');
}

OAS_version = 11;
if ((navigator.userAgent.indexOf('Mozilla/3') != -1) ||
(navigator.userAgent.indexOf('Mozilla/4.0 WebTV') != -1))
OAS_version = 10;
if (OAS_version >= 11)
document.write('<SCR' + 'IPT LANGUAGE=JavaScript1.1 SRC="' + OAS_url + 'adstream_mjx.ads/' +
OAS_sitepage + '/1' + OAS_rns + '@' +
OAS_listpos + '?' + OAS_query + '"><\/SCRIPT>');//-->


document.write('');
function OAS_AD(pos) {
 if (OAS_version >= 11)
OAS_RICH(pos);
else 
OAS_NORMAL(pos);
}

// OAS ad serving stuff 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

// Featured Pet Module (home page) START
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');
    if (awoForm) {
        awoForm.keyword.value = 'Any';
        var locValue = getCookie('location');
        if(locValue == null) {
            awoForm.location.value = 'Zip or City, State/Prov';
        }
        else {
            awoForm.location.value = locValue;
        }
    }
}

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

// 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 search = document.getElementById('search');

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

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

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

function checkInfo() {
    for (i=0;i<0;i++) {
        if(document.forms[2].elements[i].value=='') {
            alert('Required fields on this Form must be completed!');
            document.forms[2].elements[i].focus();
            return false;
        }
    }
    submitInfo();
    return true;
}

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

function getCheckValue (element) {
    if (element && element.name) {
        var value=getCookie(element.name);
        if (value>0) {
            element.checked=true;
        }
        else {
            element.checked=false;
        }
    }
}

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 submitInfo() {
        document.forms[2].submit();
        return true;
}

function checkSearch() {
    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 (animals.selectedIndex == 0 && (breed.value == '' || breed.value == null)) {
        alert('Please select an animal and-or a breed to search!');
        animals.focus();
        return false;
    }

    setCookie('pet.Animal',animals.selectedIndex,exp);
    setCookie('pet.Breed',breed.value,exp);
    setCookie('pet.Age',age.selectedIndex,exp);
    setCookie('pet.Size',size.selectedIndex,exp);
    setCookie('pet.Sex',gender.selectedIndex,exp);

    return true;
}

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

function setValue(element) {
        setCookie(element.name,element.value, exp);
}

// 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) {
    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;
}

// 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

function petNoteJs(peturl, petid) {
    document.petNote.petid.value=petid;
    var actionString = peturl + 'displaypet.cgi?petid=' + 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;
}

// replaces the zip-loc in the link with the users cookie zip-loc

function updateMorePetsZip(linkId) {
    var linkEl = document.getElementById(linkId);
    
    if (linkEl) {
        var location = getCookie('location');
        var morePetsLink = linkEl.href;
        
        if (location && morePetsLink) {
        
            // for IE and FF
            linkEl.href = morePetsLink.replace(/zip=(.*)$/,'zip=' + location);
        
            // for Safari
            linkEl.setAttribute('href', morePetsLink.replace(/zip=(.*)$/,'zip=' + location));
        }
    }
}

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


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=660,width=778,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 scrollPets(peturl, petid, prevSet, nextSet, shelterSearch) {
    si = document.scrollInfo;
    if((nextSet - 0) == 1) {
        si.idList.value = si.nextidList.value;
        if(shelterSearch) {
            si.offset.value = (si.offset.value - 0) + (si.limit.value - 0);
        }
        else {
            si.offset.value = si.nextOffset.value;
            si.zone.value = si.nextZone.value;
            si.nextOffset.value = si.nextNextOffset.value;
            si.nextZone.value = si.nextNextZone.value;
        }
    }
    if((prevSet - 0) == 1) {
        si.idList.value = si.nextidList.value;
        si.nextPage.value = 1; //if you come from a previous link there must be a next page
        if(shelterSearch) {
            si.offset.value=(si.offset.value - 0) - (si.limit.value - 0);
        }
        else {
            si.nextOffset.value=si.offset.value;
            si.nextZone.value=si.zone.value;
            si.offset.value = si.prevOffset.value;
            si.zone.value = si.prevZone.value;
        }
    }
    si.action = peturl + 'displaypet.cgi?petid=' + petid;
    si.petid.value = petid;
    si.submit();
}

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

function showBox(id) {
    box = document.getElementById(id);
    box.style.visibility = 'visible';
    box.style.position   = 'static'; 
}

// toggles the media box for the refresh, 6-2008
// 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') {
        showBox(video_box_id);
        hideBox(photo_box_id);
    } 
    else {
        hideBox(video_box_id);
        showBox(photo_box_id);
        document.masterPhoto.src = photo_url;
    }
}

// we do this via a javascript function because the currently viewed pet phot can change
// we want the user to be able to add the photo they are looking at, not just the first photo
function cheezburgerLink(photoId, linkId, petId) {
    var clink = 'http://cheezburger.com/CaptionPic.aspx?url=' + escape(document.getElementById(photoId).src) 
        + '&source=' + escape('petfinder.com') 
        + '&sourceUrl=' + escape('http://www.petfinder.com/petnote/displaypet.cgi?petid=' + petId);
    document.getElementById(linkId).href=clink;
    pageTracker._trackPageview('icanhascheezburger.com'); 
}
// 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) {
  var url = 'https://pets.petfirsthealthcare.com/petfinder/quote.aspx?pet_name=' + name + 
    '&pet_species=' + animal + '&pet_age=' + age + '&pet_breed=' + breed + '&pet_gender=' + gender;
  var petfirstwin = window.open(url, 'petfirstwin', 'width=300,height=400,left=0,top=0,resizable=yes,scrollbars=yes,toolbar=no');
  petfirstwin.focus();
  pageTracker._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="/petnote/displaypet.cgi?petid=' + pet.identifier + 
            '"><img style="width: 100px" alt="' + breed + ' Cat: ' + pet.name + '" src="' + photoBase + 
            'fotos/' + pet.shelterid + '/' + pet.shelterid + '.' + pet.identifier + '-1-pn.jpg" /></a>' + 
            '</div><a href="/petnote/displaypet.cgi?petid=' + 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";
    }
}

function saveSearchCookie() {
	
  // 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:   ''
    };
  }
  
  // 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 = '';
  }
  
  // animal type
  var animal = document.getElementById("animal_type") || document.getElementById("pet_animal_type");
  if (animal && animal.value) {
    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;
}

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

// replaces a link target with a link to the new search if the user is viewing new search info
function updateSearchLink(linkId, animal, breed) {
  var link = document.getElementById(linkId);
  if (YAHOO.util.Cookie.getSub('userPrefs', 'searchType') 
    && (YAHOO.util.Cookie.getSub('userPrefs', 'searchType') == 'new') 
    && link ) {
	  
    var target = '/pet-search?';

    var location = YAHOO.util.Cookie.getSub('userPrefs', 'location');
    if (location) {
      target += 'location=' + location + '&';
    }
    
    if (animal) {
      target += 'animal=' + animal + '&';
    }

    if (breed) {
      target += 'breed=' + breed + '&';
    }
    
    link.href = target;
  }
}


/* 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://' + window.location.hostname + '/petdetail/';
  if (searchType != 'new') {
    petUrlBase = 'http://' + window.location.hostname + '/petnote/displaypet.cgi?petid='
  }

  // 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 */

/* New search left nav stuff START */
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();
  }
}

// clear the start breed
function clearStartBreed() {
  document.getElementById('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].text && (animalObj.options[i].text == 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;
  }
}

// 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');     
  }
}

/* New search left nav stuff END */

