// Animal Management System JavaScript Library
// Copyright (c) 2004-2010 Ivor Durham. All rights reserved.

var TRUE = 1;
var FALSE = 0;

var defaultHelpPage = "";
var defaultHelpSection = "";

var adoptionProcessPopupWidth = 625;
var adoptionProcessPopupHeight = 800;

var tableRowShowStyle = navigator.appName.indexOf("Internet Explorer") >= 0 ? "block" : "table-row";

function noop() {
}

function trim(s) {
  return s.replace(/^\s*/,"").replace(/\s*$/,"");
}

function setChecked(radioList, name) {
    for (var i = 0; i < radioList.length; i++) {
        if (radioList[i].value == name) {
            radioList[i].checked = true;
        } else {
	    radioList[i].checked = false;
	}
    }
}

function getChecked(radioList) {
  for (var i = 0; i < radioList.length; i++) {
    if (radioList[i].checked) {
      return radioList[i].value;
    }
  }

  return "";
}

function getSelection(selectList) {
    return selectList.options[selectList.selectedIndex].value
}

function setSelection(selection, choice) {
    for (var i = 0; i < selection.length; i++) {
        if (selection.options[i].value == choice) {
            selection.selectedIndex = i;
            return
        }
    }

    selection.selectedIndex = 0;
}

function trimField(field) {
    field.value = trim(field.value);
}

function isValidEmailAddress(field, errorMessage) {
    var emailPattern = /^[^ ]+@[^ ]+\.[^ ][^ ]+$/;

    trimField(field);

    email = field.value;

    if (email.match(emailPattern) == null) {
	field.select();
	field.focus();
	alert(errorMessage);
	return false;
    }

    return true;
}

// A valid phone number must be at least 10 digits long

function isValidPhoneNumber(field, errorMessage) {
    var number, digits;

    trimField(field);

    number = field.value;

    digits = number.replace(/[^0-9]+/g, '');

    if (digits.length < 10) {
	field.focus();		      
	alert(errorMessage);
	return false;
    } else {
	return true;
    }
}

// A valid microchip, if not empty, is at least 9 hexadecimal digits

function isValidMicrochipID(field, errorMessage) {
    var invalidDigitPattern = /[^A-Fa-f0-9]+/;
    var validPunctuationPattern = /[ .*-]/g;

    trimField(field);

    id = field.value;

    try {
	if (id.length == 0) {
	    // Empty ID is ok
	    return true;
	}

	id = id.replace(validPunctuationPattern, '');

	if (id.search(invalidDigitPattern) >= 0) {
	    throw RangeError("invalid character(s)");
	}

	if (id.length < 9) {
	    throw RangeError("not enough digits");
	}

	return true;
    } catch (e) {
	field.select();
	field.focus();
	alert(errorMessage + ' (' + e.message + ')');
	return false;
    }
}

function isEmpty(field, errorMessage) {
    trimField(field);

    if (field.value == "") {
	field.focus();
	alert(errorMessage);
	return true;
    } else {
	return false;
    }
}

function isUnchecked(field, errorMessage) {
    if (getChecked(field) == "") {
	alert(errorMessage);
	return true;
    } else {
	return false;
    }
}

function isNumber(field, errorMessage) {
    if (isEmpty(field, errorMessage)) {
	return false;
    }

    var item = field.value; // (Trimmed in isEmpty)

    for (var j = 0; j < item.length; j++){
	var digit = item.charAt(j);
	
	if ((digit < '0') || (digit > '9')) {
	    field.select();
	    field.focus();

	    alert(errorMessage);

	    return false;
	}
    }

    return true;
}

function keyIsEnter(event) {
    var keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode);
    return (keyCode == 13);
}

function isSelected(field, errorMessage) {
    if (getSelection(field) == '') {
	field.focus();

	alert(errorMessage);

	return false;
    }

    return true;
}

function areCookiesEnabled() {
    var cookiesEnabled = (navigator.cookiesEnabled) ? true : false;

    if (typeof navigator.cookiesEnabled == "undefined" && !cookiesEnabled) { 
	document.cookie="testcookie";
	cookiesEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }
  
    return (cookiesEnabled);
}

function needCookies() {
    if (!areCookiesEnabled()) {
	alert('You must enable session cookies for this page to work.\n(Session cookies are kept only until you close your web browser.)');
    }
}

function showPopupWindow(name, url, width, height) {
    var features =
	"titlebar=yes,directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,width="+width+",height="+height;

    newWindow = window.open(url, name, features);

    if (newWindow) {
	newWindow.focus();
    }
}

function showHelpWindow(helpPage, helpSection) {
    var url;

    url = homeURI + "admin/help/help.php?page=" + helpPage;

    if (helpSection != "") {
        url = url + "&section=" + helpSection;
    }

    showPopupWindow("Help", url, 600, 400);
}

function setHelpAnchor(helpPage, helpSection) {
    defaultHelpPage = helpPage;
    defaultHelpSection = helpSection;
}

var helpIconOff = new Image();
var helpIconOn = new Image();
var helpIconInitialized = false;
var helpIconIndex = 0;

function loadHelpIcon() {
    if (!helpIconInitialized) {
	helpIconOff.src = homeURI + "images/help/help_off.gif";
	helpIconOn.src = homeURI + "images/help/help_on.gif";
	helpIconInitialized = true;
    }
}

function inlineHelpLink(helpPage, helpSection) {
    loadHelpIcon();

    overHandler = "document.images['help[" + helpIconIndex + "]'].src = helpIconOn.src";
    outHandler = "document.images['help[" + helpIconIndex + "]'].src = helpIconOff.src";

    document.write("<a href=\"javascript:showHelpWindow('" + helpPage + "', '" + helpSection + "')\"><img name=\"help[" + helpIconIndex + "]\"src=\"" + helpIconOff.src + "\" border=\"0\" height=\"16\" align=\"bottom\" onmouseover=\"" + overHandler + "\" onmouseout=\"" + outHandler + "\"></a>");

    helpIconIndex++;
}

function inlineHelpAlert(message) {
    loadHelpIcon();

    overHandler = "document.images['help[" + helpIconIndex + "]'].src = helpIconOn.src";
    outHandler = "document.images['help[" + helpIconIndex + "]'].src = helpIconOff.src";

    document.write("<a href=\"javascript:noop()\" onclick=\"alert('" + message + "')\"><img name=\"help[" + helpIconIndex + "]\"src=\"" + helpIconOff.src + "\" border=\"0\" align=\"bottom\" onmouseover=\"" + overHandler + "\" onmouseout=\"" + outHandler + "\"></a>");

    helpIconIndex++;
}

function newHelpSection(anchor, topic) {
    document.write("<p class=\"section\"><a name=\"" + anchor + "\"></a>" + topic + "</p>\n");
}

function newHelpSubsection(anchor, topic) {
    document.write("<p class=\"subsection\"><a name=\"" + anchor + "\"></a>" + topic + "</p>\n");
}

function insertSectionWithHelp(style, title, helpPage, helpSection) {
    document.write("<table cellspacing=\"0\" cellpadding=\"0\"><tr><td nowrap=\"nowrap\"><p class=\"" + style + "\" style=\"margin:0\">" + title + "</p></td><td>&nbsp;</td><td>");
    inlineHelpLink(helpPage, helpSection);
    document.write("</td></tr></table>");
}

function sectionWithHelp(title, helpPage, helpSection) {
    insertSectionWithHelp("section", title, helpPage, helpSection);
}

function subsectionWithHelp(title, helpPage, helpSection) {
    insertSectionWithHelp("subsection", title, helpPage, helpSection);
}

function showSpeciesAdoptionProcess(species) {
    showPopupWindow("AdoptionProcess", homeURI + "adoption/process.php?species=" + species, adoptionProcessPopupWidth, adoptionProcessPopupHeight);

    return false;
}

function showAdoptionProcess() {
    showSpeciesAdoptionProcess(1);
}

function showPetFinderPage(petfinderID) {
    if (petfinderID == 0) {
	return;
    }

    url = "http://www.petfinder.com/pet.cgi?action=2&pet=" + petfinderID;

    showPopupWindow("Petfinder", url, 650, 600);
}

function rule() {
    document.write("<div class=\"hr\"><hr /></div>\n");
}

// Date/Time functions

function writeDate(timestamp) {
    var ts = new Date(timestamp);

    document.write((ts.getMonth() + 1) + "/" + ts.getDate() + "/" + ts.getFullYear());
}

function writeTime(timestamp) {
    var ts = new Date(timestamp);
    var hours = ts.getHours();
    var mins = ts.getMinutes();

    if (mins < 10) {
	mins = "0" + mins;
    }

    am = hours < 13;

    if (hours == 0) {
	hours = 12;
    } else if (hours > 12) {
	hours -= 12;
    }

    document.write(" " + hours + ":" + mins + (am ? "am" : "pm"));
}

/*
  showDate

  id - ID of the field to receive the date.
 
  date - The date in YYYY-MM-DD format.

  (This function is used with the jquery DatePicker.)
 */

function showDate(id, date) {
    var element = document.getElementById(id);

    if (date != '') {
	fields = date.split('-');
	element.innerHTML = fields[1] + '/' + fields[2] + '/' + fields[0];
    }
}

/*
  showDatePreview

  ID - update for new jquery use of calendar.
 */

function showDatePreview(formName, dateField, previewID) {
    var form = document.forms[formName];

    showDate(previewID, form[dateField].value);
}

function basename(path) {
    return path.replace(/.*\//, "");
}

function writeAdoptUsLinks() {
    document.write('<tr><td valign="bottom">&nbsp;&nbsp;<font size=2 face="Geneva, Arial, Helvetica" color="#ff6633"><b>PLEASE</b></font></td></tr>');
    
    document.write('<tr>');
    document.write('<td width="75" bgcolor="#ffffcc" align="left" valign="middle">');
    document.write('<a href="catworks/adopt.html">');
    document.write('<img src="images/adopt3.jpg" border="0" width="74" alt="Please Adopt Us!"></a>');
    document.write('</td>');
    document.write('</tr>');

    document.write('<tr>');
    document.write('<td bgcolor="#ffffcc" align="center" valign="middle">');
    document.write('<a href="dogworks/gallery.php">');
    document.write('<img src="images/adoptdog1.jpg" border="0" width="74" alt="Please Adopt Us!"></a>');
    document.write('</td>');
    document.write('</tr>');
    	
    document.write('<tr>');
    document.write('<td valign="top">');
    document.write('<font size=2 face="Geneva, Arial, Helvetica" color="#ff6633"><b>ADOPT US!</b></font>');
    document.write('</td>');
    document.write('</tr>');
}

// AJAX Functions

function getXMLHTTPObject() {
    var xmlHttp=null;

    try {
	// Firefox, Opera 8.0+, Safari

	xmlHttp = new XMLHttpRequest();
    } catch (e) {
	// Internet Explorer

	try {
	    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
    }

    return xmlHttp;
}

