var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5 && Number(rslt[1]) <= 7);
if (itsAllGood)
{
	window.onerror=function()
	{
	//alert('An error has occurred!')
	return true
	}
}

// triggers functions once the dom loads (not assets like images)
document.observe("dom:loaded", function()
    {
	    recentlyViewedBreeds();
	    ie6FlickerFix();
    }
);

ie6FlickerFix = function()
{
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {}
}

//This function preloads the global navigation elements
var navRoll = false;
//Set this variable to false so no global rollovers will work until all preloading is done.
function plGnav()
{
	plImages();
	navRoll = true;
}

function plImages()
{
    var linkArray = document.getElementsByTagName("img");
    for (var loop=0; loop<linkArray.length; loop++)
    {
        if (linkArray[loop].className == "pl")
        {
			var imgPath = linkArray[loop].src.substring( 0, linkArray[loop].src.lastIndexOf( '/' ) + 1 );
			uPreload( linkArray[loop].id, imgPath, linkArray[loop].src.substring( linkArray[loop].src.lastIndexOf( '.' ) ) );
        }
    }
}

//This function preloads rollover images with a & i suffixes for active and inactive
//The function can preload any number of images.
//usage: uPreload( object name, directory of image, extension of image )
var imgSuffix = new Array('i', 'a');
function uPreload(imgName, imgPath, imgExt)
{
	for (i=0; i < imgSuffix.length; i++) {
		eval( imgName + imgSuffix[i] + " = new Image();" );
		eval( imgName + imgSuffix[i] + ".src = '" + imgPath + imgName + imgSuffix[i] + imgExt + "';" );
    }
}

//This function is for navigation rollover images; uName is name of graphic, uState is on, off or over state
function nr(uName, uState)
{
   if(navRoll)
   {
      document.images[uName].src = self[uName + uState].src;
   }
}

function drp2(uName,uState)
{
	var pFam = uName.substring(0,3); //Get parent string
	var lName = 'd' + pFam; //Make div name to show or hide
	MM_showHideLayers(lName,'',uState);	
}

function checkIt(string) 
{
var detect = navigator.userAgent.toLowerCase();
return detect.indexOf(string) + 1;
}

function MM_showHideLayers()
{
var i,p,v,obj,args=MM_showHideLayers.arguments;
for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
if (checkIt('mac')&&v=='visible') obj.pixelTop = obj.pixelTop ;
obj.visibility=v; }
}

function MM_findObj(n, d) 
{
var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function wPop(url, winName, wWidth, wHeight, scrll)
{
   var scrollB;
   if(!scrll)
   {
      scrollB = 'no';
      var pWidth = wWidth;
      var rSize = 'no';
   }
   else 
   {
      scrollB = scrll;
      wWidth = parseInt(wWidth) + 20;
      var rSize = 'yes'
   }
   var iMyWidth;
   var iMyHeight;
   wHeight = wHeight + 12;
   //Added twelve pixels to ALL popup heights to compensate for newer/larger popup header logo. 
   iMyWidth =(window.screen.width / 2) - (wWidth / 2 + 10);
   //half the screen width minus half the new window width (plus 5 pixel borders).
   iMyHeight =(window.screen.height /2) - (wHeight / 2 + 15);
   //half the screen height minus half the new window height (plus title and status bars).
   var zWin = window.open(url, winName, "status=no,width=" + wWidth + ",height=" + wHeight + ",resizable=" + rSize + ",left=" + iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + ",scrollbars=" + scrollB);
   zWin.focus();
}

// Detects if a parent window is open and loads URL into it.  Otherwise, pops a new window for URL.
function toParent(zUrl)
{
   // First check to see if there's a parent window, or a parent.parent window
   var pWin = 0;
   // Parent window is assumed closed
   if(window.opener != null && !window.opener.closed)
   {
      // One parent
      pWin = 1;
   }
   if(window.opener.opener != null && !window.opener.opener.closed)
   {
      // Two parents
      pWin = 2;
   }
   if(pWin == 0)
   {
      // Open a blank window
      var blankWin = window.open(zUrl, blankWin, "width=775,height=600,resizable=yes,left=10,top=10,screenX=10,screenY=10,scrollbars=yes,toolbar=yes,titlebar=yes,status=yes,menubar=yes,personalbar=yes,location=yes,directories=yes");
   }
   if(pWin == 1)
   {
      // Load into parent window
      opener.location.href = zUrl;
      opener.focus();
   }
   if(pWin == 2)
   {
      // Load into parent parent window
      opener.opener.location.href = zUrl;
      opener.opener.focus();
   }
}

function legal_window(url)
{
	var link = window.open(url,"legal",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,top=(20),left=(20),screenX=(20),screenY=(20),width=560,height=450');
	link.focus();
}

function wallpaper_prev(url)
{
	link = window.open(url,"wallpaper",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=no,resizable=no,top=(20),left=(20),screenX=(20),screenY=(20),width=360,height=480');
}

function phoneSelector(argURL){
        window.opener.location=argURL;  // redirect parent
        window.opener.focus();          // bring parent window to the top
        window.close();                 // close child
}

function pf() //pop-up printer friendly pages
{
	var url = window.location.href.split('#')[0];
	url += url.indexOf('?') != -1 ? '&' : '?';
	wPop( url + 'print=1', 'print', 610, 550, 'yes' );
}

function brandSelect( ddl ) {
	var s = ddl.options[ ddl.selectedIndex ].value;
	if ( s.length == 0 )
		return;
	if ( s.substring(0,11) == "javascript:" )
		eval( s.substring(11) );
	else if ( s.substring(0,4) == "http" )
		window.open( s, "_blank" );
	else
		document.location.href = s;
}

function brandPop( url ) {
	wPop( url,"brand",650,440,'yes' );
}

function brandPopLg( url ) {
	wPop( url,"brand",770,560,'yes' );
}

function emailFriend( url ) {
	wPop( url,'email_friend',310,620 );
}

function emailSmallDogFriend( url ) {
	wPop( url,'email_friend',310,630 );
}

function hugsPop( url ) {
	wPop( url,"pethugs",615,725,'yes' );
}

function rndNum(max)
{
	return Math.floor(Math.random() * max);
}

function rndLyr(ttlLyrs)
{
	document.getElementById( 'rndLyr' + rndNum(ttlLyrs) ).style.display = 'block';
}

function menuPop(url, winName, wWidth, wHeight, scrll)
{
   var scrollB;
   if(!scrll)
   {
      scrollB = 'no';
      var pWidth = wWidth;
   }
   else 
   {
      scrollB = scrll;
      wWidth = parseInt(wWidth) + 20;
   }
   var iMyWidth;
   var iMyHeight;
   wHeight = wHeight + 12;
   //Added twelve pixels to ALL popup heights to compensate for newer/larger popup header logo. 
   iMyWidth =(window.screen.width / 2) - (wWidth / 2 + 10);
   //half the screen width minus half the new window width (plus 5 pixel borders).
   iMyHeight =(window.screen.height /2) - (wHeight / 2 + 15);
   //half the screen height minus half the new window height (plus title and status bars).
   var zWin = window.open(url, winName, "menubar=yes,toolbar=no,status=no,width=" + wWidth + ",height=" + wHeight + ",resizable=no,left=" + iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + ",scrollbars=" + scrollB);
   zWin.focus();
}

function toolPop(url, winName, wWidth, wHeight, scrll)
{
   var scrollB;
   if(!scrll)
   {
      scrollB = 'no';
      var pWidth = wWidth;
   }
   else 
   {
      scrollB = scrll;
      wWidth = parseInt(wWidth) + 20;
   }
   var iMyWidth;
   var iMyHeight;
   wHeight = wHeight + 12;
   //Added twelve pixels to ALL popup heights to compensate for newer/larger popup header logo. 
   iMyWidth =(window.screen.width / 2) - (wWidth / 2 + 10);
   //half the screen width minus half the new window width (plus 5 pixel borders).
   iMyHeight =(window.screen.height /2) - (wHeight / 2 + 15);
   //half the screen height minus half the new window height (plus title and status bars).
   var zWin = window.open(url, winName, "toolbar=yes,status=no,width=" + wWidth + ",height=" + wHeight + ",resizable=no,left=" + iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + ",scrollbars=" + scrollB);
   zWin.focus();
}

function contactPop( url ) {
	toolPop( url,"contact",700,600,'yes');
}

var prefix = "Step2.aspx?cid=";

function convertImagery(modelName, url, cid, mfgid, mid)
{	//this function builds out the full path to the large image, then creates the querystring values and url for step 2 on submit
	var path = url;
	document.images['featurePhone'].src = path;
	submitButton.style.display = 'block';
	prefix = "Step2.aspx?cid=";
	prefix += cid;
	prefix += "&mfg=";
	prefix += mfgid;
	prefix += "&mid=";
	prefix += mid;
	var submitUrl = document.getElementById( "submitUrl" );
	submitUrl.href = prefix;
}

function sfHover() 
{
	var browserName=navigator.appName;
	if (browserName=="Microsoft Internet Explorer" && document.getElementById("tnav"))
	{
		var sfEls = document.getElementById("tnav").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}

AttachEvent(window, "load", sfHover);

function AttachEvent(elementObj, eventName, eventHandlerFunctionName)
{
  if (elementObj.addEventListener) 
  { // Non-IE browsers
    elementObj.addEventListener(eventName, eventHandlerFunctionName, false);		
  } 
  else if (elementObj.attachEvent) 
  { // IE 6+
    elementObj.attachEvent('on' + eventName, eventHandlerFunctionName);
  } 
  else 
  { // Older browsers 
    var currentEventHandler = elementObj['on' + eventName];
    if (currentEventHandler == null) 
    {
      elementObj['on' + eventName] = eventHandlerFunctionName;
    } 
    else 
    {
      elementObj['on' + eventName] = function(e) { currentEventHandler(e); eventHandlerFunctionName(e); }
    }
  }
}

function divDisplay(divName, displayStyle)
{
	document.getElementById( divName ).style.display = displayStyle;
}

function pausecomp(millis)
	{
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < millis);
	} 

function balloon(bElmnt,bType,bContent,addOnClick)
{
    var lnkPos = Position.cumulativeOffset(bElmnt); //Position balloon based on link location
    var wrp = $("balloon"); //Outer container for entire balloon
    var innr = $("balloonContent"); //Inner area to write content to.
    var pntr = $("balloonPointer"); //Pointer for balloon
    var wrpWidth = 0;
	var wrpHeight = 0;
    
    switch (bType)
    {
        case "wallpaper":
			//Update Content inside #balloonContent
			Element.update(innr, '<img alt="" src="../../i/downloads/wallPapers_phone/' + bContent + '.jpg" />');
			
			//Measures height of the entire wrapper (#balloon) now that content is inside
			wrpWidth = Element.getWidth(wrp);
			wrpHeight = Element.getHeight(wrp);
			
			wrp.style.width = 187 + "px";
			wrp.style.left = lnkPos[0] + 78 + "px";
			wrp.style.top = lnkPos[1] - 200 + "px";
			
			pntr.className = 'balloonPointerLeftDown';
			pntr.style.left = lnkPos[0] + 49 + "px";
			pntr.style.top = lnkPos[1] + "px";
        break;
        case "textMessage":
			Element.update(innr, '<img alt="" src="../../i/downloads/' + bContent + '.gif" />');
			
			wrp.style.width = 187 + "px";
			wrp.style.left = lnkPos[0] + 100 + "px";
			wrp.style.top = (lnkPos[1] - 150) + "px";
			
			pntr.className = 'balloonPointerLeftDown';
			pntr.style.left = lnkPos[0] + 71 + "px";
			pntr.style.top = lnkPos[1] - 25 + "px";
        break;
        case "bundle":
			Element.update(innr, '<img alt="" src="../../i/downloads/' + bContent + '.gif" />');
			
			wrp.style.width = 300 + "px";
			wrp.style.left = lnkPos[0] + "px";
			wrp.style.top = lnkPos[1] + 38 + "px";
			
			pntr.className = 'balloonPointerTopLeft';
			pntr.style.left = lnkPos[0] + 60 + "px";
			pntr.style.top = lnkPos[1] + 10 + "px";
        break;
        default :
			wrp.style.left = "-400px";
			wrp.style.height = "1px";
			pntr.style.left = "-400px";
		break;
    }
}

function bBlock()
{
	var wrp = $("balloon"); //Outer container for entire balloon
    var innr = $("balloonContent"); //Inner area to write content to.
    var pntr = $("balloonPointer"); //Pointer for balloon
    {
		pntr.className = '';
		Element.update(innr, '');
		wrp.style.width = "1px";
		wrp.style.left = "-400px";
		pntr.style.left = "-400px";
    }
}

function setFlashVar(flashObjId, flashVar, flashVarValue)
{
    window.document[flashObjId].SetVariable(flashVar,flashVarValue);
}

function checkTextBoxes(checkBoxArgs)
{
	var allElements = Form.getElements("Form1");
	for (var i=0; i<allElements.length; i++)
	{
		if (allElements[i].type == "checkbox" && !Element.hasClassName(allElements[i].parentNode, "ignore"))
		{
			$(allElements[i]).checked = false;
		}
	}
	var checkBoxes = returnArray(checkBoxArgs);
	for (var i=0; i<checkBoxes.length; i++)
	{
		$(checkBoxes[i]).checked = true;
	}
}

//Returns an array from a space separated list
function returnArray(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

//Clears a textfield when clicked.
function doClear(theText)
{
	if (theText.value == theText.defaultValue)
	{
		theText.value = ""
	}
}

//START Tooltips stuff
function pauseComp(millis)
    {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
}

function returnDimensions(elmtToClone)
{
    //Clones anchor top, left, width and height styles from element passed as elmtToCone 
	var elmntClone = $("elementClone"); //Div to clone to
	elmntClone.style.display= "block";
	Position.clone(elmtToClone, elmntClone);
	
	//Convert all positions and dimensions of cloned element to integers for resizing/repositioning
	var bTop = parseInt(elmntClone.style.top.substring(0,(elmntClone.style.top.length - 2)));
	var bLeft = parseInt(elmntClone.style.left.substring(0,(elmntClone.style.left.length - 2)));
	var bWidth = parseInt(elmntClone.style.width.substring(0,(elmntClone.style.width.length - 2)));
	var bHeight = parseInt(elmntClone.style.height.substring(0,(elmntClone.style.height.length - 2)));
	
	var dimArray = new Array()
        dimArray[0] = bTop;
        dimArray[1] = bLeft;
        dimArray[2] = bWidth;
        dimArray[3] = bHeight;
	    return(dimArray);
}

function toolTip(domKey, toolTipContent, toolTipWidth)
{   
	if (!$('toolTip'))//Only create and insert into page if it doesn't already exist.
	{
		//Create string of all elements needed for tooltip
		var ttipElmnts = '<div id="toolTip">';
		ttipElmnts += '<div id="hd" class="nosleight">';
		ttipElmnts += '<div class="c nosleight"></div>';
		ttipElmnts += '</div>';
		ttipElmnts += '<div id="bd" class="nosleight">';
		ttipElmnts += '<div class="c nosleight">';
		ttipElmnts += '<div id="toolTipContent">&nbsp;</div>';
		ttipElmnts += '</div>';
		ttipElmnts += '</div>';
		ttipElmnts += '<div id="ft" class="nosleight">';
		ttipElmnts += '<div class="c nosleight"></div>';
		ttipElmnts += '</div>';
		ttipElmnts += '</div>';
		ttipElmnts += '<a id="elementClone" onmouseout="toolTipOff()"><!-- --></a>';
		ttipElmnts += '<div id="toolTipPointer"><!-- --></div>';
		ttipElmnts += '<div id="ttipBlocker" onmouseover="toolTipOff()"><!-- --></div>';
	    
		//Insert string into body of page
		$(document.body).insert(ttipElmnts);
	}
    
    var pgWrp = $("wrap"); //Outer container for the entire webpage. We will use this to find the center of the layout on the screen.
    
    //Get the left and top pixel positions of the page wrapper
	var pPosition = Position.cumulativeOffset(pgWrp);
	
	//Get the center of the page wrapper
	var pCenter = (pPosition[0] + (pPosition[0] + pgWrp.offsetWidth))/2;
    
    //Clone the element key (the element that the user has moused over) to get dimensions and create blocker
    var lnkDimArray = returnDimensions(domKey);
    
    //Setup the blocker
    var ttipBlocker = $("ttipBlocker");
    ttipBlocker.setStyle({
		display: 'block'
	});
    
    //Write href and onclick values from element key into blocker
    if ($(domKey).readAttribute('href'))
    {
		$('elementClone').writeAttribute({
			href: $(domKey).readAttribute('href'),
			onclick: $(domKey).readAttribute('onclick')
		});
    }
    else
    {
		$('elementClone').writeAttribute({
			onclick: $(domKey).readAttribute('onclick')
		});
    }
	
	//Get the center of the element that we're trying to point off of.
	var bElmntCenter = (lnkDimArray[1] + (lnkDimArray[1] + lnkDimArray[2]))/2;
    
    var wrp = $("toolTip"); //Outer container for entire balloon.
    wrp.style.display= "block";
    var pntr = $("toolTipPointer"); //Pointer for balloon.
    var innr = $("toolTipContent"); //Inner area to write content to.
			
    //Update the innr div with our content.
    Element.update(innr,toolTipContent);
		
		//Get the height now that we've added content
		var balloonHeight = innr.getHeight();
	    
		//Decide which way to point
		if (bElmntCenter >= pCenter)//Point to the left
		{   
			wrp.style.width = toolTipWidth + "px";
			wrp.style.left = lnkDimArray[1] - toolTipWidth - 10 + "px";
    		
			pntr.className = 'toolTipPointerRightDown';
			pntr.style.left = lnkDimArray[1] - 21 + "px";
	    }
	    else //Point to the right
	    {
	        wrp.style.width = toolTipWidth + "px";
	        wrp.style.left = (lnkDimArray[1] + lnkDimArray[2]) + 14 + "px";
    		
			pntr.className = 'toolTipPointerLeftDown';
			pntr.style.left = lnkDimArray[1] + lnkDimArray[2] - 15 + "px";
	    }
	    
	    pauseComp(100); //Brief pause before doing anything.
	    
	    wrp.style.top = ((lnkDimArray[0] + Math.round(lnkDimArray[3])/2)) - balloonHeight + "px";
	    pntr.style.top = ((lnkDimArray[0] + Math.round(lnkDimArray[3])/2)) - 42 + "px";
	    wrp.style.visibility = "visible";
	    pntr.style.visibility = "visible";
}

function toolTipOff()
{
	var wrp = $("toolTip"); //Outer container for entire balloon
    var innr = $("toolTipContent"); //Inner area to write content to.
    var pntr = $("toolTipPointer"); //Pointer for balloon
    var blckr = $("elementClone"); //Blocker for link
    {   
		wrp.style.visibility = "hidden";
		wrp.style.display= "none";
		pntr.style.visibility = "hidden";
		pntr.className = '';
		blckr.style.display= "none";
		$("ttipBlocker").style.display = "none";
    }
}
//END Tooltips stuff

//Breed Library START
function breedLibraryToolTip(domKey, itemID, toolTipWidth)
{
	if($(domKey).hasClassName('brdTmb'))
	{
		var toolTipContentDiv = domKey.parentNode;
	}
	else
	{
		var toolTipContentDiv = $(domKey).ancestors();
		toolTipContentDiv = toolTipContentDiv[1];
		
	}
	toolTipContentDiv = $(toolTipContentDiv).select('div.toolTipContent');
	var innrContent = '<img class="brdMedImg" src="../../i/breed/meddog' + itemID +'.jpg" alt="" />';
    innrContent += $(toolTipContentDiv[0]).innerHTML;
    toolTip(domKey, innrContent, toolTipWidth);
}

//To update content area with a file using AJAX. url = file to get, dId = id to update to. Relies on the Javascript Prototype library.
function updateWithFile(url, dId)
{
	var myAjax = new Ajax.Updater(
				{success: dId}, 
				url, 
				{method: 'get', parameters: '', onFailure: reportError,evalScripts: true}
				);
}

//Reports generic error on Ajax Updater failure
function reportError(request)
{
	alert('We are sorry there was an error. Please try again later.');
}

function recentlyViewedBreeds()
{
	if ($('brdRecent'))
	{	
		var rcntVwd = Purina.Com.Web.Dogs.BreedLibrary.BreedLibraryAjaxUtility.GetRecentlyViewedFromSession();
		if (window.location.hostname == 'purina.preview.arcww2.com' || window.location.hostname == '63.115.253.184')
		{
			rcntVwd.value = rcntVwd.value.replace("63.115.253.184", "purina.preview.arcww2.com")
		}
		else if (window.location.hostname == '164.109.19.118')
		{
			rcntVwd.value = rcntVwd.value.replace("www.purina.com", "164.109.19.118")
		}
		updateWithFile(rcntVwd.value, "brdRecent");
	}
}

//Breed Library END

/*function popSurveyCookies()
{
   var surveyCookie = getCookie('surveyCookie');
   if(surveyCookie == null || surveyCookie == 'null' || surveyCookie == '')
	{	
		SetCookie( 'surveyCookie', 'true', 365, '/', '', '' );
	}
	else if (surveyCookie == 'true')
	{
		AttachEvent(window, "unload", popSurvey);
		SetCookie( 'surveyCookie', 'false', 365, '/', '', '' );
	}
}

function popSurvey()
{
	var surveyCookie = getCookie('surveyCookie');
	if(surveyCookie == 'false'){
		wPop('http://www.insightexpress.com/s/Puri142029', 'general', 700, 650, 'yes');
	}
}

AttachEvent(window, "load", popSurveyCookies); */
