var ajaxObjects = new Array();
var testi = 0;
var scriptDebug=false;
var ajaxErrorOccured = false;

// Browser Detection Javascript
// copyright 1 February 2003, by Stephen Chapman, Felgall Pty Ltd
// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.
function whichBrs() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
	return navigator.userAgent.substr(0,agt.indexOf('\/'));}
	else return 'Netscape';} else if (agt.indexOf(' ') != -1)
	return navigator.userAgent.substr(0,agt.indexOf(' '));
	else return navigator.userAgent;
}

//textarea popup
function openLargeTA(elementID){
  var name = "/admin/textarea?elementID="+elementID;
  var x = "600";
  var y = "600";
	doOpenWindow(name, x, y);
  //window.open(name, '_blank','width='+x+',height='+y+',resizable=yes,scrollbars=yes,status=no,menubar=no')
}

function CapFirst(field) {
	field.value = field.value.charAt(0).toUpperCase() + field.value.substring(1);
}
function CapAll(field) {
	field.value = field.value.toUpperCase();
}

function doOpenWindowNew(name, width, height) {
	dateVar = new Date();
	windowVar = dateVar.getMinutes()+''+dateVar.getSeconds();
	newwindow = window.open(name,windowVar,'width='+width+',height='+height+',resizable=yes,scrollbars=yes,status=no,menubar=no')
	if (window.focus) { newwindow.focus(); }
}

function doOpenWindow(name, width, height) {
	newwindow = window.open(name,'blank','width='+width+',height='+height+',resizable=yes,scrollbars=yes,status=no,menubar=no')
	if (window.focus) { newwindow.focus(); }
}

function openNewWindow(name) {
	doOpenWindow(name, 450, 500);
}

function openAddNewItemWindow(name) {
	doOpenWindowNew(name, 525, 500);
}

function editableShow(Id){
	document.getElementById('editable'+Id).className='editableShow';
}

function editableOff(Id){
	document.getElementById('editable'+Id).className='';
}			

function setFieldFocus(cellName) {
	var fields = document.getElementsByName(cellName);
	fields[0].focus();
	if (fields[0].type == "text" || fields[0].type == "file" || fields[0].type == "textarea") {
		fields[0].select();
	}
}

function valueInArray(val, arr) {
  for (via=0; via<arr.length; via++) {
		if (arr[via]==val) {
			return true;
		}
	}
	return false;
}

function verifyResetPassword(fieldName) {
	var fields = document.getElementsByName(fieldName);
	var field = fields[0];
	if (field.value) {
		if (verifyValidEmail(fieldName)) {
			getValueWithAjax('/info/getData?type=verifyUserWithEmailAddress&emailAddress='+field.value, 'showResetPasswordMessage("'+fieldName+'", returnedValue);');
		}
	}
}

function formValidateChangePassword(form) {
	rgValidateError = false;
	if (form.Verify.value != form.New.value) {
		form.New.value = '';
		form.Verify.value = '';
		form.New.focus();
		if (!rgValidateError) fieldFirstError = 'New';
		rgValidateError = true;
	}
	return formValidate(form);
}
function formValidateChangeUsername(form) {
	if (!form.Username.value) {
		form.Username.focus();
		alert("Username cannot be blank!")
		return false;
	}
	return true;
}

function showResetPasswordMessage(fieldName, returnedValue) {
	if (returnedValue == 0) {
		formValidationErrorWithField(fieldName, 'EmailAddressNotFound');
	} else {
		formValidationNoErrorWithField(fieldName, 'FoundAccountWithEmailAddress');
	}
}

function showChildMenuItems(parentItemID) {
	items = getElementsByName_iefix('div', parentItemID);
	for (var t=1; t<items.length; t++) {
		if (items[t].getAttribute("id") != "MenuID"+parentItemID) {
			items[t].style.display = '';
		}
	}
	content = document.getElementById('toggleMenuID'+parentItemID);
	content.innerHTML = "<a href=\"javascript:hideChildMenuItems("+parentItemID+")\" title=\"Collapse this menu\">-</a>";
	document.cookie = "Collapse"+parentItemID+"=; path=/";
}

function hideChildMenuItems(parentItemID) {
	items = getElementsByName_iefix('div', parentItemID);
	for (var t=1; t<items.length; t++) {
		if (items[t].getAttribute("id") != "MenuID"+parentItemID) {
			items[t].style.display = 'none';
		}
	}
	content = document.getElementById('toggleMenuID'+parentItemID);
	content.innerHTML = "<a href=\"javascript:showChildMenuItems("+parentItemID+")\" title=\"Expand this menu\">+</a>";
	document.cookie = "Collapse"+parentItemID+"=1; path=/";
}

function getElementsByName_iefix(tag, name) {
	var elem = document.getElementsByTagName(tag);
	var arr = new Array();
	for(i = 0,iarr = 0; i < elem.length; i++) {
		att = elem[i].getAttribute("name");
		if(att == name) {
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}

function returnCurrentDate() {
  var currentTime = new Date();
  var month = currentTime.getMonth() + 1;
  if (month < 10) month = "0" + month;
  var day = currentTime.getDate();
  if (day < 10) day = "0" + day;
  var year = currentTime.getFullYear();
  var currentDate = month + "/" + day + "/" + year;
	return currentDate;
}

function returnCurrentDateTime() {
	var currentDate = returnCurrentDate();
	var currentTime = new Date();
  var hours = currentTime.getHours();
  var minutes = currentTime.getMinutes();
  if (minutes < 10) minutes = "0" + minutes;
  if(hours > 11){
    var ampm = "PM";
    if (hours > 12) hours = hours - 12;
  } else {
    var ampm = "AM"
  }
  if (hours < 10) hours = "0" + hours;
  var currentDT = currentDate + " " + hours + ":" + minutes + " " + ampm;
  return currentDT;
}

function toggleDisplay(id) {
	obj = document.getElementById(id);
	if (obj.style.display == 'none') {
		obj.style.display = '';
	} else {
		obj.style.display = 'none';
	}
}

function createXMLHttpRequest() {
	var XMLHttpRequestObject = false;
	try {
		XMLHttpRequestObject = new ActiveXObject("MSXML2.XMLHTTP");
	} catch (exception1) {
		try {
			XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (exception2) {
			XMLHttpRequestObject = false;
		}
	}
	if(!XMLHttpRequestObject && window.XMLHttpRequest)
	{
		XMLHttpRequestObject = new XMLHttpRequest();
	}
	if(!XMLHttpRequestObject) {
		alert("We're sorry, but this web page requires a recent browser.");
	}
	return XMLHttpRequestObject;
}

// The getXMLData() function returns a value from xmlObj
function getXMLData(xmlObj) {	
  if (xmlObj[0].firstChild) {
	  if (xmlObj[0].textContent) {
		return xmlObj[0].textContent;
	  } else {
		return xmlObj[0].firstChild.data;
	  }
	} else {
		return "";
	}
}

function pleaseWaitStart(){
	  waitObj =  
	    new YAHOO.widget.Panel("wait", {
	      width:       "240px",  
	      fixedcenter: true,  
	      close:       false,  
	      draggable:   false,  
	      modal:       true, 
	      visible:     false 
	    }  
	  ); 
	  waitObj.render(document.body);
	  //waitObj.setHeader("Processing, please wait...");
	  var tempURL = location.href.split('://');	  
	  if (tempURL['0'] == 'https') {
		  waitObj.setBody('Processing... <img src="https://s3.amazonaws.com/imagesroot.rescuegroups.org/loadingcircle.gif" />');
	  } else {
		  waitObj.setBody('Processing... <img src="http://imagesroot.rescuegroups.org/loadingcircle.gif" />');
	  }	
	  waitObj.render(); 
}

function pleaseWaitOn(){
	  waitObj.show();
}
function pleaseWaitOff(){
	  waitObj.hide();
}

function viewFullsize(url,width,height){
	  fullSizeObj =  
	    new YAHOO.widget.Panel("fullSize", {  
	    	width: width+"px",
	    	height: height+"px",
	    	close:true,  
	        draggable:true,  
	        modal:true, 
	        visible:false
	    }  
	  ); 
	  fullSizeObj.render(document.body);	  
	  fullSizeObj.setHeader('&nbsp;');
	  fullSizeObj.setBody('<img src="'+url+'">');
	  fullSizeObj.setFooter('<div id="closePopUp"><a href="" onClick="fullSizeObj.hide(); return false;">Close</a></div>');
	  fullSizeObj.render();
	  fullSizeObj.center();
	  fullSizeObj.show();
	  document.getElementById("fullSize").focus();
}

function viewBreedInfo(breedID){
	  fullSizeObj =  
	    new YAHOO.widget.Panel("fullSize", {  
	    	width: "620px",
	    	close:true,  
	        draggable:true,  
	        modal:true, 
	        visible:false
	    }  
	  ); 
	  fullSizeObj.render(document.body);	  
	  fullSizeObj.setHeader('&nbsp;');
	  fullSizeObj.setBody('<iframe width="600px" height="450px" scrolling="auto" frameborder="no" src="/info/breedInfo?BreedID='+breedID+'&popup=onlyStyles">');
	  fullSizeObj.setFooter('<div id="closePopUp"><a href="" onClick="fullSizeObj.hide(); return false;">Close</a></div>');
	  fullSizeObj.render();
	  fullSizeObj.center();
	  fullSizeObj.show();
	  document.getElementById("fullSize").focus();
}

function viewFullsizeVideo(html,width,height){
	  fullSizeObj =  
	    new YAHOO.widget.Panel("fullSize", {  
	    	width: width+"px",
	    	height: height+"px",
	    	close:true,  
	        draggable:true,  
	        modal:true, 
	        visible:false
	    }  
	  ); 
	  fullSizeObj.render(document.body);	  
	  fullSizeObj.setHeader('&nbsp;');
	  fullSizeObj.setBody('<div style=height:'+height+'px;>&nbsp;'+html+'</div>');
	  fullSizeObj.setFooter('<div id="closePopUp"><a href="" onClick="fullSizeObj.hide(); return false;">Close</a></div>');
	  fullSizeObj.render();
	  fullSizeObj.center();
	  fullSizeObj.show();
	  document.getElementById("fullSize").focus();
}

/*
If you want to use this script, please keep the original author in this header!

Purpose:	Script for applying maxlengths to textareas and monitoring their character lengths.
Author: 	James O'Cull
Date: 		08/14/08

To use, simply apply a maxlenth value to a textarea.
If you need it to prevent typing past a certain point, add lengthcut="true"

Example:
<textarea maxlength="1000" lengthcut="true"></textarea>

If you add a new text area with javascript, simply call parseCharCounts() again find the new textarea(s) and label them!
*/
var LabelCounter = 0;

function parseCharCounts()
{
	//Get Everything...
	var elements = document.getElementsByTagName('textarea');
	var element = null;
	var maxlength = 9;
	var newlabel = null;
	
	for(var i=0; i < elements.length; i++)
	{
		element = elements[i];
		
		if(element.getAttribute('maxlength') != null && element.getAttribute('limiterid') == null)
		{
			maxlength = element.getAttribute('maxlength');
			
			//Create new label
			newlabel = document.createElement('label');
			newlabel.id = 'limitlbl_' + LabelCounter;
			newlabel.style.color = 'red'; //default color -- jas
			newlabel.style.display = 'block'; //Make it block so it sits nicely.
			newlabel.innerHTML = "Updating...";
			
			//Attach limiter to our textarea
			element.setAttribute('limiterid', newlabel.id);
			element.onkeyup = function(){ displayCharCounts(this); };
			
			//Append element
			element.parentNode.insertBefore(newlabel, element.nextSibling);
			
			//Force the update now!
			displayCharCounts(element);
		}
		
		//Push up the number
		LabelCounter++;
	}
}

function displayCharCounts(element)
{
	var limitLabel = document.getElementById(element.getAttribute('limiterid'));
	var maxlength = element.getAttribute('maxlength');
	var enforceLength = false;
	if(element.getAttribute('lengthcut') != null && element.getAttribute('lengthcut').toLowerCase() == 'true')
	{
		enforceLength = true;
	}
	
	//Replace \r\n with \n then replace \n with \r\n
	//Can't replace \n with \r\n directly because \r\n will be come \r\r\n

	//We do this because different browsers and servers handle new lines differently.
	//Internet Explorer and Opera say a new line is \r\n
	//Firefox and Safari say a new line is just a \n
	//ASP.NET seems to convert any plain \n characters to \r\n, which leads to counting issues
	var value = element.value.replace(/\u000d\u000a/g,'\u000a').replace(/\u000a/g,'\u000d\u000a');
	var currentLength = value.length;
	var remaining = 0;
	
	if(maxlength == null || limitLabel == null)
	{
		return false;
	}
	remaining = maxlength - currentLength;
	
	if(remaining >= 0)
	{
		limitLabel.className = 'standout'; //added to use rg styles -- jas
		limitLabel.innerHTML = remaining + ' character';
		if(remaining != 1)
			limitLabel.innerHTML += 's';
		limitLabel.innerHTML += ' remaining';
	}
	else
	{
		if (enforceLength == true) {
			value = value.substring(0, maxlength);
			element.value = value;
			element.setSelectionRange(maxlength, maxlength);
			limitLabel.className = 'standout'; //added to use rg styles -- jas
			limitLabel.innerHTML = '0 characters remaining';
		}
		else {
			//Non-negative
			remaining = Math.abs(remaining);
			
			limitLabel.className = 'standout'; //added to use rg styles -- jas
			limitLabel.innerHTML = 'Over by ' + remaining + ' character';
			if (remaining != 1) 
				limitLabel.innerHTML += 's';
			limitLabel.innerHTML += '!';
		}
	}
}

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

function clearLayoutPreviewCookies(){
createCookie("FontFamily", "","1");
createCookie("FontSize", "","1");
createCookie("FontSizeUOM", "","1");
createCookie("ColorBodyBG", "","1");
createCookie("ColorBodyFont", "","1");
createCookie("ColorSecondaryBG", "","1");
createCookie("Link","","1");
createCookie("Active", "","1");
createCookie("Visited", "","1");
createCookie("Hover", "","1");
createCookie("ColorSecondaryFont", "","1");
createCookie("SecondaryLinks", "","1");
createCookie("SecondaryActive", "","1");
createCookie("SecondaryVisited", "","1");
createCookie("SecondaryHover", "","1");
createCookie("ColorMinorbarBG", "","1");
createCookie("ColorStrongFont", "","1");
createCookie("StrongLinks","","1");
createCookie("StrongActive", "","1");
createCookie("StrongVisited", "","1");
createCookie("StrongHover", "","1");
createCookie("LayoutID", "","1");
}

function viewDetailPopover(animalID){
	if (!animalID) return false;
	popOverObj =  
		new YAHOO.widget.Panel('animalDetails', {  
    	width:'600px',
    	height:'490px',
        close:true,  
        draggable:true,  
        modal:true, 
        visible:false,
        constraintoviewport:true,
        underlay:'none'
	    }  
      );  
  popOverObj.setBody('<div class="bdContent">'+
		  '<div><iframe id="detailFrame" width="590px" height="400px" scrolling="auto" frameborder="no" src="/animals/details?animalID='+animalID+'"></iframe></div>'+
		  '</div>'+
		  '<div id="closeAnimalDetails">'+
		  '<a id="closeMe" href="" onClick="popOverObj.setBody(\'\'); popOverObj.hide(); return false;">Close</a>'+
		  '</div>');
  popOverObj.render(document.body);	 
  popOverObj.center();
  popOverObj.show();
  document.getElementById('animalDetails').focus();
}