var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var Mac = (navigator.appVersion.indexOf("Mac")!=-1);

var jsFlashInterface =
{
	setFlashSize: function(el,flash,width,height)
	{
		$("#"+el).css({"width":width,"height":height});
		document.getElementById(el).style.width = width+"px";
		document.getElementById(el).style.height = height+"px";
	}
}

function setFlashSize(el,flash,width,height)
{
	$("#"+el).css({"width":width,"height":height});
	document.getElementById(el).style.width = width+"px";
	document.getElementById(el).style.height = height+"px";
}

var jsNavigation = 
{
	heroNavItems: 0,
	minHeight: 119,

	initTopNav: function() 
	{
		$("div.menu ul.nav ul").each(function(i) 
		{
		    var m_numTwoRowHeight = 20;
		    var m_numDefaultTop = 21;
            var m_numTwoRowHeightFlag = false;
		    var m_numTop = 0;
		
			if($(this).parents("ul").length == 1)
			{
				$(this).css({"position":"relative"}).children("li").each(function(i) {					
				    // make this flag false as we are starting a new section
				    if( i == 0 ) 
				    {
				        m_numTwoRowHeightFlag = false;
				        m_numTop = 0;
				    }
				    else
				    {
				        m_numTop += m_numDefaultTop;
				    } // if
				    
				    // add 20 pixels to match the two row height
				    if( m_numTwoRowHeightFlag ) 
				    {
				        m_numTop += m_numTwoRowHeight;
				        m_numTwoRowHeightFlag = false;
                    } // if
				    
				    // the next item needs the additional pixel size
				    if( $(this).children("a").attr("class") == "tworows" )
				    {
				        m_numTwoRowHeightFlag = true;
				    } // if
				       
					$(this).css({"position":"absolute","left":0,"top":m_numTop}).children("ul").css({"position":"absolute","left":200,"top":0});
				});
			}
		});
		
		$("div.menu ul.nav li ul.flyleft").css({"position":"absolute","right":200});

		if(IE6)
		{
			$("div.menu ul.nav li").hover(
				function() 
				{
					$(this).addClass("on");
				},
				function ()
				{
					$(this).removeClass("on");
				}
			);
		}

		if(Mac)
		{
			$("div.menu").hover(
				function() 
				{
					$("#flashPetPriority").hide();
				},
				function ()
				{
					$("#flashPetPriority").show();
				}
			);
		}
	},

	initHeroNav: function()
	{	

		$(".contentBody div.hero div.left div.heronav ul li ul").each(function(i)
		{
			$(this).attr("id","heroNav"+i).parent("li").attr("id","heroNavItem"+i);
		});

		$(".contentBody div.hero div.left div.heronav ul li ul").each(function(i)
		{
			$(this).remove().addClass("herosubnav").css({"left":180}).clone().appendTo("div.contentBody").hover(
				function()
				{
					$(this).show();
					$("#"+$(this).attr("id").replace("heroNav","heroNavItem")).addClass("on");
				},
				function()
				{
					$(this).hide();
					$("#"+$(this).attr("id").replace("heroNav","heroNavItem")).removeClass("on");
				}
			);
		});

		$(".contentBody div.hero div.left div.heronav ul li").hover(
			function() 
			{
				if($(this).parents("ul").length == 1)
				{
					var position = jsNavigation.getPosition($(this))+1;
					
					if($(this).attr("id"))
					{
						var length = $("#"+$(this).attr("id").replace("Item","")).children("li").length;
						
						if(length < position)
						{
							var items = $(this).parent("ul").children("li").length;

							if(IE6)
							{
								$("#"+$(this).attr("id").replace("Item","")).css({"top":(228+(items*25)-(length*25))}).show();
							}
							else
							{
								$("#"+$(this).attr("id").replace("Item","")).css({"top":(223+(items*25)-(length*25))}).show();
							}
						}
						else
						{
							if(IE6)
							{
								$("#"+$(this).attr("id").replace("Item","")).css({"top":225}).show();
							}
							else
							{
								$("#"+$(this).attr("id").replace("Item","")).css({"top":220}).show();
							}
						}
					}
					$(this).addClass("on");
				}
			},
			function ()
			{
				if($(this).parents("ul").length == 1)
				{
					if($(this).attr("id"))
					{
						$("#"+$(this).attr("id").replace("Item","")).hide();
					}
					$(this).removeClass("on")
				}
			}
		);
	},

	initSubNav: function()
	{
		if(window.location.href.indexOf("article.aspx") != -1)
		{
			var queryString = window.location.search;

			$(".contentBody div.body div.top div.left ul.subnav li span").siblings("ul").toggle();
			
			$(".contentBody div.body div.top div.left ul.subnav li ul li a").each(function()
			{	
				if($(this).attr("href").indexOf(queryString) != -1)
				{
					$(this).addClass("on").parent("li").parent("ul").toggle().siblings("span").toggleClass("on");
				}

				//if($(this).text().length > 40)
				//{
				//	$(this).parent("li").css({"height":40});
				//}
			});

			$(".contentBody div.body div.top div.left ul.subnav li span").click(function() 
			{
				$(this).toggleClass("on").siblings("ul").toggle();
			});
			
			if($("ul.subnav").length > 0 && $("div.layoutSmallTabs").length > 0)
			{
				this.minHeight = parseInt($("ul.subnav").css("height"))+144;
				
				if($("div.featuredProduct").length > 0)
				{
					this.minHeight += 195;
				}
			}
			
			$(".layoutOnePanel div div").each(function(i)
			{
				if(parseInt($(this).css("height")) < jsNavigation.minHeight)
				{
					$(this).css({"height":jsNavigation.minHeight});
				}
			});	
		}
	},
	
	initBreadCrumb: function()
	{
	    if ($("#BreadCrumb-Parent")!=null)
	    {
	        $("#BreadCrumb-Parent").html("<a href='default.aspx'>" + $(".sectTil").text() + "</a>");
	        $("#BreadCrumb-Child").html($("span.on").text());
	        $("#BreadCrumb-GrandChild").html($("a.on").text());
	    }
	},

	getPosition: function(el)
	{
		var position = 0;

		while(el.prev().length > 0)
		{
			position++;
			el = el.prev();
		}

		return position;
	}
}

var jsProductRotator = 
{
	delay: 12,
	step: null,

	init: function()
	{
		$(".featuredProduct div img").attr("id","rotatorImage");

		$(".btnPlay").click(function()
		{
			jsProductRotator.toggle(this);
		});

		$(".btnBack").click(function()
		{
			jsProductRotator.back();
		});

		$(".btnForward").click(function()
		{
			jsProductRotator.forward();
		});

		if(typeof jsFeaturedProducts != "undefined")
		{
			jsProductRotator.step = window.setTimeout(jsProductRotator.next,(1000*jsProductRotator.delay));
		}
	},

	toggle: function(button)
	{
		if(this.step == null)
		{
			$(button).attr("src",$(button).attr("src").replace("-play","-pause"));
			jsProductRotator.step = window.setTimeout(jsProductRotator.next,(1000*jsProductRotator.delay));
		}
		else
		{
			$(button).attr("src",$(button).attr("src").replace("-pause","-play"));
			window.clearTimeout(this.step);
			this.step = null;
		}
	},

	back: function()
	{
		if(this.step == null)
		{
			this.rotate(-1);
		}
		else
		{
			window.clearTimeout(this.step);
			this.step = null;
			jsProductRotator.rotate(-1);
			jsProductRotator.step = window.setTimeout(jsProductRotator.next,(1000*jsProductRotator.delay));
		}
	},

	forward: function()
	{
		if(this.step == null)
		{
			this.rotate(1);
		}
		else
		{
			window.clearTimeout(this.step);
			this.step = null;
			jsProductRotator.rotate(1);
			jsProductRotator.step = window.setTimeout(jsProductRotator.next,(1000*jsProductRotator.delay));
		}
	},

	next: function()
	{
		jsProductRotator.rotate(1);
		jsProductRotator.step = window.setTimeout(jsProductRotator.next,(1000*jsProductRotator.delay));
	},

	rotate: function(direction)
	{
		var current = null;
		
		$.each(jsFeaturedProducts, function(i,n)
		{	
			if($("#rotatorImage").css('filter'))
			{
				if(document.getElementById("rotatorImage").filters(0).src.indexOf(n.img) != -1)
				{
					current = i;
				}
			}
			else
			{
				if(n.img == $(".featuredProduct div img").attr("src"))
				{
					current = i;
				}
			}
		});

		if(direction > 0)
		{
			current++;
		} else {
			current--;
		}

		if(current < 0)
		{
			current = jsFeaturedProducts.length-1;
		}

		if(current > jsFeaturedProducts.length-1)
		{
			current = 0;
		}
		
		if($("#rotatorImage").css('filter'))
		{
			document.getElementById("rotatorImage").filters(0).src = jsFeaturedProducts[current].img;
			$(".featuredProduct div img").attr("alt",jsFeaturedProducts[current].alt);
		}
		else
		{
			$(".featuredProduct div img").attr("src",jsFeaturedProducts[current].img).attr("alt",jsFeaturedProducts[current].alt);
		}

		$(".featuredProduct div a").attr("href",jsFeaturedProducts[current].url);
	}
}

var jsCountrySelect =
{
	init: function()
	{
		$(".jsSelectCountry").css({"cursor":"pointer"}).click(function() {$(".jsSelectCountryList").show();});

		$(".jsSelectCountryList").hover(
			function() {
			},
			function() {
				$(".jsSelectCountryList").hide();
			}
		);
	},

	click: function(href)
	{
		if($("#setCntry").get(0).checked)
		{
			var expdate = new Date();
			expdate.setTime(expdate.getTime()+(60*60*24*365*1000));
			document.cookie = "PurinaIntl06=" + href + "; expires=" + expdate.toGMTString() + "; path=/";
		}
		window.location.href = href;
	}
}

var jsTabs =
{
    id: 8,
    minHeight: 119,

    init: function(tab) {
        if ($("ul.subnav").length > 0 && $("div.layoutSmallTabs").length > 0) {
            this.minHeight = parseInt($("ul.subnav").css("height")) + 144;
        }

        this.bind(".layoutSmallTabs");
        this.bind(".layoutLargeTabs");

        $(".layoutSmallTabs ul.tabs li:first").click();

        if (tab == null || tab == "") {
            $(".layoutLargeTabs ul.tabs li:first").click();
        }
        else {
            $(".layoutLargeTabs ul.tabs li").each(function(i) {
                if (i == tab) {
                    $(this).click();
                }
            });
        }
    },

    bind: function(tabs) {
        if (tabs == ".layoutLargeTabs") {
            if ($(".layoutLargeTabs > div").length > 1) {
                $(".layoutLargeTabs > div").each(function(i) {
                    if (parseInt($(this).css("height")) > jsTabs.minHeight) {
                        jsTabs.minHeight = parseInt($(this).css("height"));
                    }
                });
            }

            $(".layoutLargeTabs div div.pngfix").each(function(i) {
                if (parseInt($(this).css("height")) < jsTabs.minHeight) {
                    $(this).css({ "height": jsTabs.minHeight });
                }
            });
        }

        $(tabs).each(function(i) {
            $(this).children("ul.tabs,ul.multi").each(function(j) {
                $(this).children("li").each(function(k) {
                    $(this).click(function() {
                        jsTabs.on(this);

                        $(this).siblings("li").each(function(i) {
                            jsTabs.off(this);
                        });

                        $(this).parents(tabs).children("div").each(function(l) {
                            if (l == k) {
                                $(this).show();
                            }
                            else {
                                $(this).hide();
                            }
                        });
                    });
                });
            });
        });
    },

    on: function(el) {
        $(el).children("img").each(function(i) {
            $(this).attr("src", $(this).attr("src").replace("-off", "-on"));

            if ($(this).css('filter')) {
                if (!$(this).attr("id")) {
                    $(this).attr("id", "tab" + (jsTabs.id++));
                }

                var img = document.getElementById($(this).attr("id"));
                //var current = img.filters(0).src;
                //img.filters(0).src = current.replace("-off", "-on");
                var current = img.src;
                img.src = current.replace("-off", "-on");
            }
        });
        $(el).css({ 'cursor': 'default' });
    },

    off: function(el) {
        $(el).children("img").each(function(i) {
            $(this).attr("src", $(this).attr("src").replace("-on", "-off"));

            if ($(this).css('filter')) {
                if (!$(this).attr("id")) {
                    $(this).attr("id", "tab" + (jsTabs.id++));
                }

                var img = document.getElementById($(this).attr("id"));
                //var current = img.filters(0).src;
                //img.filters(0).src = current.replace("-on", "-off");
                var current = img.src;
                img.src = current.replace("-on", "-off");                
            }
        });
        $(el).css({ 'cursor': 'pointer' });
    }
}

var jsPickYourPet =
{
	init: function()
	{
		$("#heroDogsRule,#heroRolloverDogsRule").hover(
			function() 
			{
				$("#heroRolloverDogsRule").show();
			},
			function ()
			{
				$("#heroRolloverDogsRule").hide();
			}
		);

		$("#heroCatsRule,#heroRolloverCatsRule").hover(
			function() 
			{
				$("#heroRolloverCatsRule").show();
			},
			function ()
			{
				$("#heroRolloverCatsRule").hide();
			}
		);
	}
}

var jsRollovers =
{
	init: function()
	{
		$("img.rollover").hover(
			function() 
			{
				$(this).attr("src",$(this).attr("src").replace("-out.","-over."));
				//alert( $(this).runtimeStyle.filter);
				//alert($(this).attr("src"));
			},
			function ()
			{
				$(this).attr("src",$(this).attr("src").replace("-over.","-out."));
			}
		);
		
		$("input.rollover").hover(
			function() 
			{
				$(this).attr("src",$(this).attr("src").replace("-out.","-over."));
				//alert( $(this).runtimeStyle.filter);
				//alert($(this).attr("src"));
			},
			function ()
			{
				$(this).attr("src",$(this).attr("src").replace("-over.","-out."));
			}		
		);
	}
}

var jsTools =
{
	init: function()
	{
		$("ul.tools li:first-child a").attr("href","javascript:void(0);");
		$("ul.tools li:first-child").click(function()
		{
			window.print();
		});
	}
}

var jsPetFacts =
{
	delay:12,

	init: function()
	{
		if($(".petFacts div").length > 1)
		{
			window.setTimeout(jsPetFacts.next,(1000*jsPetFacts.delay));
		}
	},

	next: function()
	{
		var current = null;
		var next = null;

		$(".petFacts div").each(function(i) 
		{
			if($(this).css("display") != "none")
			{
				current = $(this);
			}
		});

		if(current.next("div").length == 0)
		{
			next = $(".petFacts div").get(0);
		}
		else
		{
			next = current.next("div").get(0);
		}

		current.fadeOut('slow');
		$(next).fadeIn('slow');

		window.setTimeout(jsPetFacts.next,(1000*jsPetFacts.delay));
	}
}

var jsPopup =
{
	init: function()
	{	
		$("a.jsPopup").each(function()
		{
			$(this).attr("target","").attr("popup",$(this).attr("href")).attr("href","javascript:void(0);");
		});

		$("a.jsPopup").attr("target","").click(function()
		{
			window.open($(this).attr("popup"),"aPopup","width=415,height=300");
		});
	}
}

window.onload = function() 
{
	jsCountrySelect.init();

	jsNavigation.initTopNav();
	jsNavigation.initHeroNav();
	jsNavigation.initSubNav();
    jsNavigation.initBreadCrumb();

	jsProductRotator.init();
	jsTabs.init(getQueryParamValue("tab"));

	jsPickYourPet.init();
	jsRollovers.init();

	jsTools.init();
	jsPetFacts.init();
	jsPopup.init();
	
	$(".cookieKitten,.cookiePuppy,.cookieCat,.cookieDog").click(function() {$.cookie("petPref",$(this).attr("class"),{expires:30});});

    $('.postalCode').blur(
        function()
        {
            var toParse = this.value.toUpperCase();
            try
            {
                var partA = toParse.substring(0,3);
                var partB = toParse.substring(toParse.length-3, toParse.length);
                this.value = partA + " " + partB;
            }
            catch(e)
            {
                this.value = toParse;
            }
        }
    );
    
    
    $('.contentBody div.layoutBeneful div.formBeneful div.GalleryInner fieldset.Buttons div.Button').hover(
        function()
        {
            $(this).css('background-image', 'none');
        },
        function()
        {
            if (this.getAttribute('ignore')!='true')
                $(this).css('background-image', 'url(/images/beneful/backgrounds/Gallery-Tab.jpg)');
        }
    );
    
    $('.ImageRollover').hover(
        function()
        {
            this.src = this.getAttribute('on');
        },
        function()
        {
            this.src = this.getAttribute('off');
        }
    );
};

  $(document).ready(function()
    {
        if (jQuery.browser.msie && jQuery.browser.version=='6.0')
        {
            //$('.contentBody div.layoutBeneful div.formBeneful div.formField div.label').css('margin-left', '10px');
            $('.contentBody div.layoutBeneful div.formBeneful div.formCopy').css('margin-left', '8px');
            $('.contentBody div.layoutBeneful div.formBeneful div.Gallery').css('margin-left', '8px');
            $('#layoutBenefulInnerInnerDiv').css('height', '503px');
            //$('.contentBody div.layoutBeneful div.formBeneful div.formField div.BenefulRegister p').css('display','block');
            //$('.contentBody div.layoutBeneful div.formBeneful div.formField div.BenefulRegister p').css('display','inherit');
            $('.contentBody div.layoutBeneful div.formBeneful').css('width', '950px');
            $('.contentBody div.layoutBeneful div.formBeneful div.formField div.BenefulRegister p').css('width','420px');
            $('.contentBody div.layoutBeneful div.formBeneful div.GalleryInner fieldset.Content div.GalleryContent').css('margin-left', '2px');
            $('.contentBody div.layoutBeneful div.formBeneful div.GalleryInner fieldset.Content div.GalleryContent').css('padding-left', '2px');
            $('.contentBody div.layoutBeneful div.formBeneful div.GalleryInner fieldset.Content div.GalleryContent div.GalleryItemLarge').css('margin-left', '8px');
            $('.contentBody div.layoutBeneful div.formBeneful div.GalleryInner fieldset.Content div.GalleryContent').css('width', '620px');
            $('.contentBody div.layoutBeneful div.formBeneful div.GalleryInner fieldset.Content div.GalleryContent fieldset.Options').css('width', '620px');
            $('#GalleryContent').css('width', '620px');
        };
    });
    var LT = new RegExp("<", "g");  
    var GT = new RegExp(">", "g");  
    var AMP = new RegExp("&", "g");  
    var TAB = new RegExp("\t", "g");  


function CreateXml(id)
{
    if (id==null || id=='')
        return '';
    var outputXml = CreateXmlFromClass($(id));
    return outputXml
}

function XmlEncode(value)
{
    return value.replace(LT, "&lt;").replace(GT, "&gt;").replace(AMP,"&amp;").replace(TAB, "    ");  
}

function getValue(xmldoc, node_name)
{
    var tmp;
    tmp = xmldoc.getElementsByTagName(node_name).item(0).textContent;
    if (tmp==null)
        tmp = xmldoc.getElementsByTagName(node_name).item(0).text;
    return tmp;
}

function CreateXmlFromClass(XNode)
{
    var css_class_name;
    var xml_node_name;
    var element_prefix;
    var xml_namespace = '';
    var tagName = XNode.attr('tagName');
    //Split the id on the delimiter to find out the xml node name
    var ids = XNode.attr('id').split('-');    
    if (parseInt(ids[ids.length-1])>0)
        xml_node_name = ids[ids.length-2];
    else
        xml_node_name = ids[ids.length-1];

    if (tagName!='INPUT' && tagName!='TEXTAREA' && tagName!='SELECT')
    {
        var outputXml = '<' + xml_node_name + xml_namespace + '>';
        var nodes = $('#' + XNode.attr('id') + ' .' + XNode.attr('id'));
        for (var x=0; x<nodes.length; x++)
            outputXml = outputXml + CreateXmlFromClass($('#' + nodes[x].id))
        return outputXml + '</' + xml_node_name + '>';
    }
    else if (tagName=='INPUT' || tagName=='TEXTAREA' || tagName=='SELECT')
    {
        return '<' + xml_node_name + '>' + XmlEncode(XNode.val()) + '</' + xml_node_name + '>';
    }
}

/*
	Desc: Tracks the cta click using hitbox
	Param:	_strHBXpn - page
			_strHBXmlc - url
*/
function TrackCouponCTA( _strHBXpn, _strHBXmlc )
{
	_hbPageView( _strHBXpn, _strHBXmlc );
} // TrackCouponCTA

/*
    Desc: This will shrink the welcome kit flash in FF only
    Param: N/A
*/
function WelcomeKitResize()
{
    document.getElementById("flashWelcomeKit").style.width = "150px";
} // WelcomeKitResize