
function getObject(obj) {
  var theObj;
  if(document.all) {
    if(typeof obj=="string") {
      return document.all(obj);
    } else {
      return obj.style;
    }
  }
  if(document.getElementById) {
    if(typeof obj=="string") {
      return document.getElementById(obj);
    } else {
      return obj.style;
    }
  }
  return null;
}


function toCount(entrance,exit,text,characters) {
  var entranceObj=getObject(entrance);
  var exitObj=getObject(exit);
  var length=characters - entranceObj.value.length;
  if(length <= 0) {
    length=0;
    text='<span class="disable"> '+text+' </span>';
    entranceObj.value=entranceObj.value.substr(0,characters);
  }
  exitObj.innerHTML = text.replace("{CHAR}",length);
}


function addsmiley(code)
{
var pretext = document.forums.message2.value;
              this.code = code;
              document.forums.message2.value = pretext + code;
}

	
var menuwidth='150px' 
var menubgcolor='/images/table_gradent1.png' 
var disappeardelay=300 
var hidemenu_onclick="yes"

var ie4=document.all
var ns6=document.getElementById&&!document.all
if (ie4||ns6)
document.write('<div id="dropmenudiv" style="visibility:hidden;width:'+menuwidth+';" background="/images/table_gradent1.png" onMouseover="clearhidemenu()" onMouseout="dynamichide(event)"></div>')
function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}
function showhide(obj, e, visible, hidden, menuwidth){
if (ie4||ns6)
dropmenuobj.style.left=dropmenuobj.style.top="-500px"
if (menuwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=menuwidth
}
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}
function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}
function populatemenu(what){
if (ie4||ns6)
dropmenuobj.innerHTML=what.join("")
}
function dropdownmenu(obj, e, menucontents, menuwidth){
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById? document.getElementById("dropmenudiv") : dropmenudiv
populatemenu(menucontents)
if (ie4||ns6){
showhide(dropmenuobj.style, e, "visible", "hidden", menuwidth)
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
}
return clickreturnvalue()
}
function clickreturnvalue(){
if (ie4||ns6) return false
else return true
}
function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}
function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}
function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}
function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}
function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}
if (hidemenu_onclick=="yes")
document.onclick=hidemenu

function priceCheck(id) {
	window.open("http://www.verpets.com/pricecheck.php?id="+id+"", "priceChecker", "status=0, toolbar=0, location=0, menubar=0, directories=0, resizeable=0, width=250, height=350");
}

// shoutbox stuff \\

var shoutroom;
	
function refreshShoutBox () {
	new Effect.Appear('shoutboxloading', { duration: 0.4 });
	new Ajax.Request('http://www.verpets.com/shoutbox/shout.php?room='+shoutroom+'&rand='+Math.random()+'&reverse='+reverseSB,
	  {
		method:'get',
		onSuccess: function(transport){
		 $('shoutbox').innerHTML=transport.responseText;
		// doUserMouseovers();
		 //doPetMouseovers();
		 new Effect.Fade('shoutboxloading', { duration: 0.4 });
		},
		onFailure: function(){ alert('Shoutbox Error!') }
	  });
}

function postShout () {
	new Effect.Appear('shoutboxloading', { duration: 0.4 });
	var message = $('shoutMessage').value;
	$('shoutMessage').value='';
	new Ajax.Request("http://www.verpets.com/shoutbox/shout.php?message="+message+"&room="+shoutroom+'&rand='+Math.random()+'&reverse='+reverseSB,
	  {
		method:'get',
		onSuccess: function(transport){
		 $('shoutbox').innerHTML=transport.responseText;
		 new Effect.Fade('shoutboxloading', { duration: 0.4 });
		},
		onFailure: function(){ alert('Shoutbox Error!') }
	  });
}

function deleteShout (id) {
	if (!confirm('Are you sure you want to delete this shout?')) {
		return;
	}
	new Effect.Appear('shoutboxloading', { duration: 0.4 });
	var message = $('shoutMessage').value;
	$('shoutMessage').value='';
	new Ajax.Request("http://www.verpets.com/shoutbox/shout.php?deleteid="+id+"&room="+shoutroom+'&rand='+Math.random()+'&reverse='+reverseSB,
	  {
		method:'get',
		onSuccess: function(transport){
		 $('shoutbox').innerHTML=transport.responseText;
		 new Effect.Fade('shoutboxloading', { duration: 0.4 });
		},
		onFailure: function(){ alert('Shoutbox Error!') }
	  });
}

function shoutTimeout (username) {
	if (!confirm('Are you sure you want to timeout this user?')) {
		return;
	}
	new Effect.Appear('shoutboxloading', { duration: 0.4 });
	$('shoutMessage').value='';
	new Ajax.Request("http://www.verpets.com/shoutbox/shout.php?timeout="+username+"&room="+shoutroom+'&rand='+Math.random()+'&reverse='+reverseSB,
	  {
		method:'get',
		onSuccess: function(transport){
		 $('shoutbox').innerHTML=transport.responseText;
		 new Effect.Fade('shoutboxloading', { duration: 0.4 });
		},
		onFailure: function(){ alert('Shoutbox Error!') }
	  });
}
  
 function lockInRoom (username, roomid, time) {
	if (!confirm('Are you sure you want to lock this user in room #'+roomid+'???')) {
		return;
	}
	new Effect.Appear('shoutboxloading', { duration: 0.4 });
	$('shoutMessage').value='';
	new Ajax.Request("http://www.verpets.com/shoutbox/shout.php?lockuser="+username+"&roomid="+roomid+'&time='+time+'&rand='+Math.random()+"&room="+shoutroom,
	  {
		method:'get',
		onSuccess: function(transport){
		 $('shoutbox').innerHTML=transport.responseText;
		 new Effect.Fade('shoutboxloading', { duration: 0.4 });
		},
		onFailure: function(){ alert('Shoutbox Error!') }
	  });
}
  
function setShoutRoom (room) {
	shoutroom=room;
	$('shoutbox').innerHTML="Joining Selected Room";
	refreshShoutBox();
}
  
new PeriodicalExecuter(refreshShoutBox, 20);

function closeShoutbox () {
	new Effect.BlindUp($('shoutbox-content'));
	new Ajax.Request("http://www.verpets.com/shoutbox/openclose.php?rand="+Math.random());
	//$('shoutbox-header').innerHTML='<a href="javascript:;" onclick="return openShoutbox();"><img SRC="http://images.verpets.com/layout/new-'+STYLE+'/shoutbox-closed.png" border="0"></a>';
	$('shoutbox-header').className='moduleHeader shoutboxClosed';
}

function openShoutbox () {
	new Effect.BlindDown($('shoutbox-content'));
	new Ajax.Request("http://www.verpets.com/shoutbox/openclose.php?rand="+Math.random());
	//$('shoutbox-header').innerHTML='<a href="javascript:;" onclick="return closeShoutbox();"><img SRC="http://images.verpets.com/layout/new-'+STYLE+'/shoutbox-open.png" border="0"></a>';
	$('shoutbox-header').className='moduleHeader shoutboxOpen';
}

/**** clockkkk ***////

var serverdate=new Date(currenttime)

function padlength(what){
var output=(what.toString().length==1)? "0"+what : what
return output
}

function amPMsymbol(x){
   return (x>11)?'PM':'AM';
}

function leadingZero(x){
   return (x>9)?x:'0'+x;
}

function twelveHour(x){
   if(x==0){
      x=12;
   }
   return (x>12)?x-=12:x;
}

function displayTime(){
	serverdate.setSeconds(serverdate.getSeconds()+1)
	var timestring=padlength(twelveHour(serverdate.getHours()))+":"+padlength(leadingZero(serverdate.getMinutes()))+":"+padlength(leadingZero(serverdate.getSeconds())+" "+amPMsymbol(serverdate.getHours()));
	
	if (div = document.getElementById('time'))
	{
		div.innerHTML=timestring;
	}
}
 
setInterval('displayTime()', 1000);		

/********** pet scroller for new layout ******/

function prevPet() {
	if (petinfoLoading == true) return;
	
	if (currpet==0) {
		currpet=(numpets-1);
		showPet();
	} else {
		currpet--;
		showPet();
	}
}

function nextPet() {
	if (petinfoLoading == true) return;

	if (currpet==(numpets-1)) {
		currpet=0;
		showPet();
	} else {
		currpet++;
		showPet();
	}
}

function autoNextPet () {
	if (petinfoExtendid != 0) return;
	nextPet();
}

var petsShowing = false;

function initPetShow () {
	if (!$('petname')) {
		setTimeout('initPetShow();', 250);
		return;
	}
	
	petsShowing = true;
	new PeriodicalExecuter(autoNextPet, 10);
	showPet();
}

function showPet() {
	$('petname').innerHTML=pets[currpet][1];
	$('petmood').innerHTML='<img SRC="http://images.verpets.com/outof10/'+pets[currpet][4]+'.png" width="87" height="9" />';
	$('pethunger').innerHTML='<img SRC="http://images.verpets.com/outof10/'+pets[currpet][2]+'.png" width="87" height="9" />';
	$('pethealth').innerHTML='<img SRC="http://images.verpets.com/outof10/'+pets[currpet][3]+'.png" width="87" height="9" />';
	$('petimg').innerHTML='<a href="http://www.verpets.com/pet/'+pets[currpet][1]+'"><img SRC="http://images.verpets.com/'+pets[currpet][5]+'" border="0" /></a>';
	$('miniStatus').innerHTML=pets[currpet][6];
	$('viewFeedLink').innerHTML='<a href="http://www.verpets.com/pet/feeds.php?petid='+pets[currpet][7]+'"><font style="font-size: 9px;">view feed &raquo;</font></a>';
	$('petidholder').innerHTML=pets[currpet][7];
	
	if (petinfoExtendid != 0) petinfo_doextend(pets[currpet][7]);
}

var petinfoExtendid = 0;
var petinfoLoading = false;
var petinfoInside = false;

function petinfo_extend (petid) {

	if (petsShowing == false) return;

	petinfoInside = true;
	petinfoExtendLoading = true;
	setTimeout('petinfo_doextend('+petid+');', 750);

}

function petinfo_doextend (petid) {

	if (petinfoInside == false) {
		petinfoLoading = false;
		return;
	}
	
	if (petinfoExtendid == petid) return;
	
	petinfoLoading = true;

	if (petinfoExtendid != 0) {
		
		new Effect.Fade('pets-extended-content', {duration: 0.3, queue: 'end', afterFinish: function (effect) {
		
			$('pets-extended-content').innerHTML = '<center><img SRC="'+IMAGESURL+'layout/new-green/petinfo-extend-load.gif" style="margin-top: 10px;"></center>';
		
		}});
		
	} else {
		
		$('pets-extended').style.display = 'block';
		$('pets-extended-content').innerHTML = '<center><img SRC="'+IMAGESURL+'layout/new-green/petinfo-extend-load.gif" style="margin-top: 10px;"></center>';
		
	}
	
	petinfoExtendid = petid;
	
	new Effect.Morph('pets-extended-contain', {style: 'height: 42px', duration: 0.2, queue: 'end'});
	new Effect.Appear('pets-extended-content', {duration: 0.3, queue: 'end', afterFinish: function (effect) {
	
		new Ajax.Request(SITEURL+'/pet/info-extend.php?petid='+petid+'&rand='+Math.random(),
		{
			method:'get',
			onSuccess: function (r) {
			
				if (petid != petinfoExtendid) return;
			
				new Effect.Fade('pets-extended-content', {duration: 0.3, queue: 'end'});
			
				if (r.responseText == 'error') {
					//alert('Error getting pet extended info!');
					
					petinfo_extend_close();
					
					return;
				}
				
				$('pets-extended-content').innerHTML = r.responseText;
				
				// hack: grab height by showing and then quickly hiding element
				$('pets-extended-content').style.display = 'block';
				var height = $('pets-extended-content').offsetHeight;
				$('pets-extended-content').style.display = 'none';
				
				new Effect.Morph('pets-extended-contain', {style: 'height: '+height+'px', duration: 0.4, queue: 'end'});
				new Effect.Appear('pets-extended-content', {duration: 0.3, queue: 'end', afterFinish: function (effect) {
					petinfoLoading=false;
				}});				
	
			},
			onFailure: function(){
			
				//alert('Error getting pet extended info!');
				
				petinfo_extend_close();
				
				return;
				
			}
		});
	
	}});
	
}

function petinfo_extend_close () {
	
	petinfoInside = false;
	
	if (petinfoExtendid == 0) return;
	if (petinfoLoading) return;
	
	petinfoExtendid = 0;
	
	new Effect.Fade('pets-extended-content', {duration: 0.2, queue: 'end'});
	
	new Effect.Morph('pets-extended-contain', {style: 'height: 0px', duration: 0.3, queue: 'end', afterFinish: function (effect) {
		
		$('pets-extended').style.display='none';
		$('pets-extended-contain').style.height='0px';
		$('pets-extended-content').style.display='none';
		petinfoLoading=false;
	
	}});
	
}

function petinfo_extend_mouseout (e) {
	if (!e) var e = window.event;
	
	//if (petinfoExtendid == 0) return;
	
	var from = (window.event) ? e.srcElement : e.target; 
	var to = (e.relatedTarget) ? e.relatedTarget : e.toElement; 
	
	if (to.id == 'petimg' || from.id == 'petimg' || to.id == 'pets') {
	
		//console.log('EXIT CAUSE '+to.id);
		return;
	
	}

	//console.log(from.id + ' => ' + to.id);

	var doClose = true;
	
	var parents = to.ancestors();
	
	//console.log('to = '+to.innerHTML);
	//console.log('from = '+from.innerHTML);
	
	var i;
	
	for (i=0;i<parents.length;i++) {
		if (parents[i].id == 'pets') {
			doClose = false;
			//console.log('Found PETS as parent of '+to.id);
			break;
		}
		//console.log('found '+parents[i].id);
	}
		
	if (doClose == true) {
		//console.log('DID NOT FIND AS PARENT OF '+to.id);
		petinfo_extend_close();
	}
}

function getPetInfo (petid) {	
	var index = window['petid2index'+petid];	
	return pets[index];
}

/********* USER MOUSEOVER THINGIES - NEEDS TO BE REDONE CAUSE FIREFOX DOESN'T LIKEY MUCH! **********/
function mouseOverUser (linkid, userid, username) {
	if (!$(linkid).prototip) {
	if ($(linkid).offsetLeft > 600) {
		var stemming = 'topRight';
	} else {
		var stemming = 'topLeft';
	}
	new Tip($(linkid), {ajax: {
    url: 'http://www.verpets.com/usermouseover.php?id='+userid,
    options: {
      method: 'get'
    }
  },
title : username,
style: 'default',
target: $(linkid),
hook: { target: 'bottomMiddle', tip: stemming },
stem: stemming,
width: 'auto',
hideOn: false,
border: 5,
radius: 3,
hideAfter: 0.1
});

}

//$(linkid).prototip.show();

}

function doUserMouseovers () {
	$$('a.ulink').each(function(element) {
		var info = element.className.split(" ");
		mouseOverUser(element.id, info[1], info[2]);
	});
}

// AND FOR PETS

function mouseOverPet (linkid, petid, petname) {
	if (!$(linkid).prototip) {
	if ($(linkid).offsetLeft > 600) {
		var stemming = 'topRight';
	} else {
		var stemming = 'topLeft';
	}
	new Tip($(linkid), {ajax: {
    url: 'http://www.verpets.com/petmouseover.php?id='+petid,
    options: {
      method: 'get'
    }
  },
title : petname,
style: 'default',
target: $(linkid),
hook: { target: 'bottomMiddle', tip: stemming },
stem: stemming,
width: 'auto',
hideOn: false,
border: 5,
radius: 3,
hideAfter: 0.1
});

}

}

function doPetMouseovers () {
	$$('a.plink').each(function(element) {
		var info = element.className.split(" ");
		mouseOverPet(element.id, info[1], info[2].substr(8));
	});
}

// AND FOR ITEMS

function mouseOverItem (linkid, itemid, itemname) {
	if (!$(linkid).prototip) {
	if ($(linkid).offsetLeft > 600) {
		var stemming = 'topRight';
	} else {
		var stemming = 'topLeft';
	}
	new Tip($(linkid), {ajax: {
    url: 'http://www.verpets.com/itemmouseover.php?id='+itemid,
    options: {
      method: 'get'
    }
  },
title : itemname.replace(/\_/g,' '),
style: 'default',
target: $(linkid),
hook: { target: 'bottomLeft', tip: stemming },
stem: stemming,
width: 'auto',
hideOn: false,
border: 5,
radius: 3,
hideAfter: 0.1,
offset: { x: 0, y: -10 }
});

}

}

function doItemMouseovers () {
	$$('a.ilink').each(function(element) {
		var info = element.className.split(" ");
		mouseOverItem(element.id, info[1], info[2]);
	});
}

/**** check all checkboxes in form **/

function checkAll(df) {
	for (var i=0; i<df.length; i++) {
		if (df[i].type=='checkbox') { df[i].checked = true; }
	}
	return false;
}

/* set opacity of div object, value = 0 - 10 */

function setOpacity(obj,value) {
	obj.style.opacity = value/10;
	obj.style.filter = 'alpha(opacity=' + value*10 + ')';
}


function shoutboxEnter(evt) {
	var charCode = (evt.which) ? evt.which : window.event.keyCode; 
	if (charCode == 13) { 
		$('shoutboxform').submit();
	} 
}

/** check all radios on a form ***/

function check(field) {
    for (i = 0; i < field.length; i++) {
       field[i].checked = true;}
}


function ucfirst (string) {
	return string.slice(0,1).toUpperCase() + string.slice(1);
}

/**** ****/
// Page width/height info
function getPageSize() {
	        
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	return [pageWidth,pageHeight];
	
}

// number format a number
function number_format (number) {
	var decimals = 0;
	var dec_point = '.';
	var thousands_sep = ',';
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "," : dec_point;
	var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

// Get selected radio button

function $RF(el, radioGroup) {
	    if($(el).type && $(el).type.toLowerCase() == 'radio') {
	        var radioGroup = $(el).name;
	        var el = $(el).form;
	    } else if ($(el).tagName.toLowerCase() != 'form') {
	        return false;
	    }
	 
	    var checked = $(el).getInputs('radio', radioGroup).find(
	        function(re) {return re.checked;}
	    );
	    return (checked) ? $F(checked) : null;
}

/***** ****/
// Overlay for lightbox
function showOverlay () {
	var arrayPageSize = getPageSize();
	$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
	new Effect.Appear('overlay', {duration: 0.75});
}

function hideOverlay () {
	new Effect.Fade('overlay', {duration: 0.75, queue: 'end'});
}

/****** DOM OBSERVER *******/
document.observe('dom:loaded', function() {
  doUserMouseovers(); doPetMouseovers(); doItemMouseovers();
});
