$(document).ready(function(){
	faqDropdown();
	setupPuppy();
	
	$('.tub_color').mouseover(function(){
		var pos = $(this).attr('rel');
		popUpShow(pos);
	});

	$('.tub_color').mouseout(popUpHide);
});

function resize(h) { 
	document.getElementById("content_ifr").style.height=h+1+"px";
}

document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	var elemLength = elem.length;
	for (var i = 0; i < elemLength; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

/*Loads special js.css stylesheet.*/

var cssTest = document.getElementsByTagName('link');
var cssTestLength = cssTest.length;
for(var cssLoop = 0; cssLoop < cssTestLength; cssLoop++) {
	if(cssTest[cssLoop].getAttribute('rel').indexOf('style') != -1 && cssTest[cssLoop].getAttribute('title') == 'js') {
		cssTest[cssLoop].disabled = true; //Addresses the buggy tauntings of IE.
		cssTest[cssLoop].disabled = false;
	}
}

/*Query string parsing.*/
var explode = function(item,delimiter) {
	tempArray=new Array(1);
	var Count=0;
	var tempString=new String(item);
	while (tempString.indexOf(delimiter)>0) {
		tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
		tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
		Count=Count+1
	}
	tempArray[Count]=tempString;
	return tempArray;
}

parseQuery = function() {
	var returnVals = new Array();
	var qString = new String(window.location);
	var queryStart = qString.indexOf('?');
	if (queryStart==-1) {
		return returnVals;
	}
	var query = qString.substring(queryStart + 1, qString.length);
	parts = explode(query, "&");
	for (i in parts) {
		bits = explode(parts[i], "=");
		returnVals[bits[0].toLowerCase()] = bits[1]; // query[] indexes are now lowercase!
	}
	return returnVals;
}

var query = parseQuery();

/*Cookies*/
createCookie = function(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

/*General Setup*/
setup = function() {
	if(document.getElementById('ruleslink')) {
		document.getElementById('ruleslink').onclick=function(){
			popWin(this,'rulesPage',450,500);
			return false;
		}
	}
	return true;
	/*Removes leftmost padding/border from footer links.*/
	var d = document.getElementById('footer').getElementsByTagName('ul')/*[0].childNodes[1]*/
	var dl = d.length;
	for (var loop=0; loop < dl; loop++) {
		d[loop].childNodes[1].style.borderStyle = "none";
		d[loop].childNodes[1].style.paddingLeft = 0;
	}
	

}

function homepageFix() {
	if(readCookie('visitHome') == "2") {
		try{clearTimeout(homeTime);}
		catch(e){}
		homepageRestore();
		return true;
	}
	if(readCookie('loadCheck') =='1') {
		homeTime = setTimeout("homepageFix()",1000)	
	}
	else {
		createCookie('loadCheck','1');
	}
	var x = (document.all) ? "-1" : 0;
	document.getElementById('footer').style.zIndex = x;
}

function homepageRestore() {
	/*Resets to default styles.*/
	if(document.body.className.indexOf('home') != -1) {
		document.getElementById('footer').style.zIndex="" 
	}
}


/* FAQ Functions*/

function faqDropdown() {
	if(document.getElementById('selProducts')) {
		var form=document.getElementById('selProducts');
		var formLong = form.length;
		for(var loop=0; loop<formLong; loop++) {
			form.onchange=function(){
				window.location = "/"+this.value+".aspx"
			}
		}
	}
}

/*Meet the Puppy Functions*/
function showContent() {
	var currentDiv = this.getAttribute('rel');
	
	// had to create special video logic so that two ads don't run simultaneously in IE6
	if ($('body').hasClass('ad')){
		var currentDivID = "#" + currentDiv;
		var currentVidCode = $(currentDivID).html();
		$("#puppyvidcontent").html(currentVidCode);
	} else {
		document.getElementById(previousDiv).style.display="none";	
		document.getElementById(currentDiv).style.display="block";
	}
	
	for(var loop = 0; loop<gridlength; loop++) {
		gridlinks[loop].className = ""
	}
	if(this.className == "") {/*Workaround for non-grid links that need to show/hide.*/		
		this.className = "current";
	}
	previousDiv = currentDiv;	
	return false;
}

function setupPuppy(){
	if(document.getElementById('selectiongrid')) {
		grid = document.getElementById('selectiongrid');
		gridlinks = grid.getElementsByTagName('a');
		gridlength = gridlinks.length;
		// had three games and videos and four of everything else...
		if ($('body').hasClass('game') || $('body').hasClass('ad') ){
			var show = (typeof(gridlinks[query['s']]) != 'undefined') ? query['s'] : 2;
		} else {
				var show = (typeof(gridlinks[query['s']]) != 'undefined') ? query['s'] : 3;
		}
		previousDiv = gridlinks[show].getAttribute('rel');
		
		// had to create special video logic so that two ads don't run simultaneously in IE6
		if ($('body').hasClass('ad')){
			var previousDivID = "#" + previousDiv;
			var previousVidCode = $(previousDivID).html();
			$("#puppyvidcontent").html(previousVidCode);
		} else {
			document.getElementById(previousDiv).style.display="block";
		}
		gridlinks[show].className = "current";
		if(document.getElementById('selectiongrid').className != 'showflash') {
			for(var sgloop=0; sgloop<gridlength; sgloop++) {
				gridlinks[sgloop].onclick = showContent;
			}
		}
		
		if(document.getElementById('shareLink') && typeof(query['s']) != 'undefined') {
			var ds = document.getElementById('shareLink');
			ds.href = ds.href + "?s=" + query['s'];
		}
	}
	
	if(document.getElementById('printcontent')){
		printLinks = document.getElementById('printcontent').getElementsByTagName('a');
		printLength = printLinks.length;
		for (var pLoop=0; pLoop < printLength; pLoop++) {
			printLinks[pLoop].onclick = printFeature;
		}
	}
	
	if(document.getElementById('instructlink')){
		document.getElementById('instructlink').onclick = showContent;
	}
}

function printFeature() {
	var openWin = window.open("","winPrint","height=300, width=300, resizable=1");
	openWin.document.body.style.margin = 0;
	openWin.document.body.innerHTML= '<img src="'+this+'">';
	var thisImg = openWin.document.getElementsByTagName('img');

	function resizeWin() {
		if(thisImg['0'].complete) {
			var w = thisImg['0'].width;
			var h = thisImg['0'].height;
			if(window.innerHeight) {
				openWin.innerHeight = h;
				openWin.innerWidth = w;
			}
			else {
				openWin.window.resizeTo(w,h)
			}
			openWin.print();	
		}
		else {
			var time = setTimeout(resizeWin,100)		
		}
	}
	resizeWin();
	return false;
}

function searchPage()
{
if(document.getElementById("searchfield").value != "" && document.getElementById("searchfield").value != "Search our site" )
{
    window.location.href="search_results.aspx?q="+document.getElementById("searchfield").value;
}
else
{
    alert("please Enter Search Text");
    document.getElementById("searchfield").focus();
    document.getElementById("searchfield").value ='';
    return false;
}
}
function SetText()
{
if (document.getElementById("searchfield").value =="Search our site")
{
document.getElementById("searchfield").value ='';
document.getElementById("searchfield").focus();
}

}

popWin= function(URL,windowName,width,height) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = Math.round((w-width)/2);
	var topPos = Math.round((h-height)/2);
	var defaults = "scrollbars=1, resizable";//"scrollbars, resizable, menubar, toolbar, location, directories, status";
	var centerOnScreen = "top="+topPos+", left="+leftPos+", width="+width+", height="+height;
	var options = centerOnScreen + " ," + defaults;
	var msgWindow = window.open(URL,windowName,options);
	if(!msgWindow) {
		return false;
	} else {
		msgWindow.focus();
	}
	return true;
};

function bannerOpen () {
	$("#topbanner").animate({top: 0}, 600).click(function () {
		createCookie("bannerclosed", "true");
	});
	$("#wrapper").css("position", "relative").animate({top: 60}, 600);
	$("body").css({backgroundPosition: "0px 0px"}).animate({backgroundPosition: "(0 60px)"}, 600);
}

function bannerClose () {
	$("#topbanner").animate({top: -60}, 600);
	$("#wrapper").animate({top: 0}, 600);
	$("body").animate({backgroundPosition: "(0px 0px)"}, 600);
	createCookie("bannerclosed", "true");
	return false;
}

/**
* Tub Overlays/Popups
* Invoked via $(document).ready() at top.
**/
function popUpShow(bgPos){
	bgPos = bgPos || 0;
	var $t = $('#tub_popup');
	var $i = $t.find('img');
	$i.css('backgroundPosition','0 '+bgPos+'px');
	$t.show();
}

function popUpHide(){
	$('#tub_popup').hide();
}


/**
 * @author Alexander Farkas
 * v. 1.02
 */
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];
            
           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);