//  window.moveTo(0,0);
//  window.resizeTo(window.screen.availWidth, window.screen.availHeight);

var whndl;
/*
var lc = location.href.toLowerCase();

var x = lc;
var lcchg = false;
   lcarq = lc.split("?");
   lcard = lcarq[0].split("/");
   lcarp = lcard[2].split(".");
   if (lcarp.length == 2) {
     lcarp.unshift("www");
     lcchg = true;
   }
   if (lcarp[1]=="caveam") {
     lcarp[1] = "caveadullamministries";
     lcchg = true;
   }
   if (lcchg) {
     x = lcarp.join(".");
     lcard[2] = x;
     x = lcard.join("/");
     lcarq[0] = x;
     x = lcarq.join("?");
     location.href = x;
   }
*/

function writeCookie(name,value) {
  var a = arguments.length;
  var yr = "2023";
  if (arguments.length == 3) {
      yr = arguments[2];
  }
  var today = new Date();
  var the_date = new Date("December 31, " + yr);
  var the_cookie_date = the_date.toGMTString();
  var the_cookie = name+"="+value;
  var the_cookie = the_cookie + ";path=/;expires=" + the_cookie_date;
  document.cookie=the_cookie;
}

function writeCart2(frm){
  var ino = document.getElementById(frm+'itemnbr').value;
  var qty = document.getElementById(frm+'qty').value;
  var cst = document.getElementById(frm+'itemcost').value;
  var ado = document.getElementById(frm+'audio').value;
  var shp = document.getElementById(frm+'shipping').value;
//alert(ino + ' ' + qty + ' ' + shp);	
  if (ino=='DONATION') {
    obj = document.getElementById(frm+'itemcost');
  } else {
    obj = document.getElementById(frm+'qty');
  }
  if (chkNumeric(obj,0, 999999999999,'','.','') == false) {
    if (ino=='DONATION') {
      document.getElementById(frm+'itemcost').value = "";
    } else {
    document.getElementById(frm+'qty').value = "";
    }
    return;
  }
  if (ado != "") {
    if (qty > 1) {
      alert('Audio download quantity may not exceed 1.');
      document.getElementById(frm+'qty').value = 1;
      qty = 1;
    }
  }
  if (ino=='ondemand') {
    if (qty > 1) {
      alert('On Demand subscription quantity may not exceed 1.');
      document.getElementById(frm+'qty').value = 1;
      qty = 1;
    }
  }
  writeCookie("cart-"+ino,qty+"<br>"+cst+"<br>"+ado+"<br>"+shp);
  if (ino=='DONATION') {
    opener.document.getElementById(frm+'itemcost').value = numberFormat(cst,2);
    document.getElementById(frm+'itemcost').value = numberFormat(cst,2);
    document.getElementById(frm+'extprc').innerHTML = numberFormat(cst,2);
    document.getElementById(frm+'lcst').innerHTML = numberFormat(cst,2);
    document.getElementById(frm+'itemcost').value = "";
  } else {
    opener.document.getElementById(frm+'qty').value = qty;
    document.getElementById(frm+'eqty').innerHTML = qty;
    document.getElementById(frm+'qty').value = "";
    document.getElementById(frm+'extprc').innerHTML = numberFormat(cst*qty,2);
  }
  var t = document.getElementsByTagName('SPAN');
  var prc = 0.00;
  for (i=0;i<t.length;i++) {
    if ((t[i].className) && (t[i].className == 'extprc')) {
//      alert(t[i].className + ' ' + t[i].innerHTML);
      prc += parseFloat(t[i].innerHTML);
    }
  }
  document.getElementById('spnTot').innerHTML = prc.toFixed(2);
}

function writeCart3(e,frm,typ){
var keynum
var keychar
var numcheck
  if(window.event) { // IE
    keynum = e.keyCode;
  } else {
    if(e.which) { // Netscape/Firefox/Opera
      keynum = e.which;
    }
  }
  keychar = String.fromCharCode(keynum);
  if (keynum == 13) {
    if (typ == "P") {
      writeCart(frm);
    } else {
      writeCart2(frm);
    }
    return false;
  } else {
    return true;
  }
}

function CheckOut(site) {
// add inventory chech here reload cartview if problem
//alert(1);	
	var http = getHTTPObject();
	var dt = new Date();
//alert(2);	
	var carterr = 0;
	var cartyes = "no";
	var f = document.getElementsByName("itemnbr");
	var s = "";
	var endit = "no";
//alert(3);	
	
  function afterAjax() {
//alert(1);	
    if (http.readyState == 4) {
      if (http.status == 200) {
//alert(http.responseText);
        var res = http.responseText.split("\r\n")[0];
				var ar = res.split("\t");
				if (ar[0] != "OK") { carterr = 1 };
				if (ar[1] == "yes") { cartyes = "yes" };
/*
				if (ar[0] != "OK") { carterr = 1 };
				if (ar[1] == "yes") {
					if (carterr == 1) {
				  	window.location = "cartview.php?err=yes";
					} else { 
  					opener.window.location = "checkout.php";
						window.innerWidth = 0;
						window.innerHeight = 0;
						window.screenX = screen.width;
						window.screenY = screen.height;
  					opener.window.focus();
					  window.close();
					}
				}
*/				
      }
    }
  }

	for (i=0;i<f.length;i++) {
//alert(4);	
		if (f[i].value == "") { continue };
		x = f[i].value + "eqty";
		var z = document.getElementById(x);
		qty = document.getElementById(x).innerHTML;
		if (i == f.length - 1) { endit = "yes" };
//alert(5);	
		AjaxSendRequest(http,"ajax2.php","func=verifyqty&itemno="+f[i].value+"&qty="+qty + "&endit="+endit,afterAjax,false);
//alert(6);	
	}
//				if (cartyes == "yes") {
//alert(7);	
					if (carterr == 1) {
				  	window.location = "cartview.php?err=yes";
					} else { 
  					opener.window.location = "checkout.php";
						window.innerWidth = 0;
						window.innerHeight = 0;
						window.screenX = screen.width;
						window.screenY = screen.height;
  					opener.window.focus();
					  window.close();
					}
//				}
	
}

function DoSubmitCheckOut() {
  if ((document.frm.night_phone_a.value.length !=3) ||
      (document.frm.night_phone_b.value.length !=3) ||
      (document.frm.night_phone_c.value.length !=4)) {
       alert('Please ensure your phone number is entered and correctly formatted.');
  } else {
     if (document.frm.email.value.length ==0) {
         alert('Please enter your email address.');
     } else {
      document.frm.submit();
     }
  }
}

function state(name) {
  for (var i=0;i<document.frm.bstate.options.length;i++) {
    if (name == document.frm.bstate.options[i].text) {
      document.frm.bstate.selectedIndex = i;
    }
  }
}

function DoCheck() {
  if (document.frm.C1.checked) {
      document.frm.bfname.value = document.frm.first_name.value;
      document.frm.blname.value = document.frm.last_name.value;
      document.frm.baddr1.value = document.frm.address1.value;
      document.frm.baddr2.value = document.frm.address2.value;
      document.frm.bcity.value = document.frm.city.value;
      state(document.frm.state[document.frm.state.selectedIndex].text);
      document.frm.bzip.value = document.frm.zip.value;
  } else {
      document.frm.bfname.value = '';
      document.frm.blname.value = '';
      document.frm.baddr1.value = '';
      document.frm.baddr2.value = '';
      document.frm.bcity.value = '';
      document.frm.bstate.selectedIndex = 0;
      document.frm.bzip.value = '';
  }
}

function checkNumeric(objName,minval, maxval,comma,period,hyphen)
{
	var numberfield = objName;
	if (chkNumeric(objName,minval,maxval,comma,period,hyphen) == false)
	{
		numberfield.select();
		numberfield.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function chkNumeric(objName,minval,maxval,comma,period,hyphen) {
// only allow 0-9 be entered, plus any values passed
// (can be in any order, and don't have to be comma, period, or hyphen)
// if all numbers allow commas, periods, hyphens or whatever,
// just hard code it here and take out the passed parameters
var checkOK = "0123456789" + comma + period + hyphen;
var checkStr = objName;
var allValid = true;
var decPoints = 0;
var allNum = "";
  for (i = 0;  i < checkStr.value.length;  i++)
  {
    ch = checkStr.value.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
    if (ch != ",")
      allNum += ch;
  }
  if (!allValid)
  {
    alertsay = "Entry may only be a positive number";
//    alertsay = "Please enter only these values \""
//    alertsay = alertsay + checkOK + "\" in the \"" + checkStr.name + "\" field."
    alert(alertsay);
    return (false);
  }

// set the minimum and maximum
var chkVal = allNum;
var prsVal = parseInt(allNum);
  if (chkVal != "" && !(prsVal >= minval && prsVal <= maxval))
  {
    alertsay = "Entry may only be a positive number";
//    alertsay = "Please enter a value greater than or "
//    alertsay = alertsay + "equal to \"" + minval + "\" and less than or "
//    alertsay = alertsay + "equal to \"" + maxval + "\" in the \"" + checkStr.name + "\" field."
//    alert(alertsay);
    return (false);
  }
}


function DoLoad(err) {
  if (window.opener && !window.opener.closed) {
    self.focus();
		if (err == "yes") {
			alert("Sorry, but one or more of your items has been reduced in quantity " +
					  "due to a sale made before your checkout.\n\n\nPlease review your " +
						"cart and continue shopping or check out again.");
		}
  } else {
    window.location = "products.php";
  }
}

function DoSubmit(frm) {
  document.frm.submit();
}

/*
function writeCart(itemno,qty,cost)
{
//alert(itemno + ' ' + qty + ' ' + cost);
  writeCookie("cart-"+itemno,qty+"<br>"+cost);
  document.frm2.swt.value = 'Y';
  //window.location = "products.php";
  viewCart();
  //whndl.focus();
}
*/

function writeCart(frm) {
  var ino = document.getElementById(frm+'itemnbr').value;
  var qty = document.getElementById(frm+'qty').value;
  var cst = document.getElementById(frm+'itemcost').value;
  var ado = document.getElementById(frm+'audio').value;
  if (ino=='DONATION') {
    obj = document.getElementById(frm+'itemcost');
  } else {
    obj = document.getElementById(frm+'qty');
  }
  if (chkNumeric(obj,0, 999999999999,'','.','') == false) {
    if (ino=='DONATION') {
      document.getElementById(frm+'itemcost').value = "";
    } else {
    document.getElementById(frm+'qty').value = "";
    }
    return;
  }
//  if (ado.value != "") {
  if (ado != "") {
    if (qty > 1) {
      alert('Audio download quantity may not exceed 1.');
      document.getElementById(frm+'qty').value = 1;
      qty = 1;
    }
  }
  if (ino=='ondemand') {
    if (qty > 1) {
      alert('On Demand subscription quantity may not exceed 1.');
      document.getElementById(frm+'qty').value = 1;
      qty = 1;
    }
  }
  writeCookie("cart-"+ino,qty+"<br>"+cst+"<br>"+ado);
  viewCart();
}

function viewCart() {
	var pw = pageWidth() - 100;
//alert(pageWidth() + ' ' + pw);
//alert('width=' + pw + ',height=500,top=0,left=0,menubar=no,toolbar=no,resizable=yes,status=yes,scrollbars=yes');	
  whndl = window.open('cartview.php','camcart','width=' + pw + ',height=500,top=0,left=0,menubar=no,toolbar=no,resizable=yes,status=yes,scrollbars=yes');
}

function closeCart() {
//  if (document.frm2.swt.value =='N') {
      whndl = window.open('','camcart');
     whndl.close();
//  } else {
//    document.frm2.swt.value = 'N';
//  }
}

function setSwt() {
//alert(window.name);
//	if (window.name != "cavenetproductlist") {
//		alert("Sorry, you must be logged in to access this page");
//	}
  window.name = 'camproducts';
//  document.frm2.swt.value = 'N';
}

function numberFormat(num,dec)
{
mul=Math.pow(10,dec);
num=num*mul;
num=Math.round(num);
num = num/mul;
var numstr=String(num);
if(numstr.indexOf(".") == -1)
{
numstr = numstr + ".";
for(nfi=0;nfi<dec;nfi++) numstr = numstr + "0";
}
decpl = numstr.length - numstr.indexOf(".");
decpl = decpl - 1;
if (decpl < dec)
{
for(nfi=decpl;nfi<dec;nfi++) numstr = numstr + "0";
}
return (numstr);
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that
// (a) you leave this copyright notice intact, and
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function URLEncode(v)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = v;
	var encoded = "";
  try {
	  for (var i = 0; i < plaintext.length; i++ ) {
		  var ch = plaintext.charAt(i);
	      if (ch == " ") {
		      encoded += "+";				// x-www-urlencoded, rather than %20
		  } else if (SAFECHARS.indexOf(ch) != -1) {
		      encoded += ch;
		  } else {
		      var charCode = ch.charCodeAt(0);
			  if (charCode > 255) {
			      alert( "Unicode Character '"
                          + ch
                          + "' cannot be encoded using standard URL encoding.\n" +
				            "(URL encoding only supports 8-bit characters.)\n" +
						    "A space (+) will be substituted." );
				  encoded += "+";
			  } else {
				  encoded += "%";
				  encoded += HEX.charAt((charCode >> 4) & 0xF);
  				encoded += HEX.charAt(charCode & 0xF);
	  		}
		  }
	  } // for
  } catch(theErr) {
    alert('Encode Error ***'+v+'***');
  }

//	document.URLForm.F2.value = encoded;
//	return false;
  return encoded;
};

function URLDecode(v)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef";
   var encoded = v;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2)
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
//   document.URLForm.F1.value = plaintext;
//   return false;
  return plaintext;
}

/*
function getHTTPObject() {
var xmlhttp;
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
     try {
         xmlhttp = new XMLHttpRequest();
     } catch (e) {
         xmlhttp = false;
     }
  } else {
      if (window.ActiveXObject) { // IE
         try {
             xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
           try {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
         }
      }
  }
  return xmlhttp;
}
*/
 
function setCookie (name, value, hours, path, domain, secure) {
var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
    document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') +
				((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':'');
}

function getCookieVal(offset) {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1) endstr = document.cookie.length;
   return unescape (document.cookie.substring(offset, endstr));
}
function getCookie(name) {
   var arg = name+"=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen) {
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) break;
   }
   return null;
}

function lTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

function rTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

function trim( value ) {
	return lTrim(rTrim(value));
}

function enterKey(func) {
  if (window.event.keyCode == '13') {
    x = new func;
    return false;
  }
  return true;
}

function noEnterKey(func) {
  if (window.event.keyCode == '13') {
    return false;
  }
  return true;
}

function sortlist(elem) {
var lb = document.getElementById(elem);
arrTexts = new Array();

  for(i=0; i<lb.length; i++)  {
    arrTexts[i] = new Array();
    arrTexts[i][0] = lb.options[i].text;
    arrTexts[i][1] = lb.options[i].value;
  }

  arrTexts.sort();

  for(i=0; i<lb.length; i++)  {
    lb.options[i].text = arrTexts[i][0];
    lb.options[i].value = arrTexts[i][1];
  }
}

function removeItems(nm) {
var l = document.getElementById(nm);
  while (l.options.length > 0) {
    l.options[0] = null;
  }
}

function isNumeric(str){
var rtn = true;
	if (str.length == 0) {
    rtn = false;
  } else {
	 for (var i=0;i<str.length;i++) {
	   chr = str.substring(i,i+1);
	   if ("1234567890-.".indexOf(chr,0) == -1) {
       rtn = false;
	     break;
	   }
	 }
  }
  return rtn;
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth() {
  return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}
function pageHeight() {
  return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}
function posLeft() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}
function posTop() {
  return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}
function posRight() {
  return posLeft()+pageWidth();
}
function posBottom() {
  return posTop()+pageHeight();
}

function printThis() {
  window.print();
}

function completeTransaction(tx) {
  writeCookie('download-' + tx,'');
  writeCookie('trans','complete');
}

function clearCart(site) {
  whndl = window.open(site+'/paypal/clearcart.php','','width=10,height=10,top=0,left=0,menubar=no,toolbar=no,resizable=no,status=no,scrollbars=no');
//  whndl.close();
}

// Object Functions
// copyright Stephen Chapman, 4th Jan 2005
//  you may copy these functions but please keep the copyright notice as well
function objWidth(objectID) {
var obj = xDOM(objectID,0);
if(obj.offsetWidth) return  obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
function objHeight(objectID) {
var obj = xDOM(objectID,0);
if(obj.offsetHeight) return  obj.offsetHeight;
if (obj.clip) return obj.clip.height;
return 0;
}
function objLeft(objectID) {
var obj = xDOM(objectID,0);
var objs = xDOM(objectID,1);
if(objs.left) return objs.left;
if (objs.pixelLeft) return objs.pixelLeft;
if (obj.offsetLeft) return obj.offsetLeft;
return 0;
}
function objTop(objectID) {
var obj = xDOM(objectID,0);
var objs = xDOM(objectID,1);
if(objs.top) return objs.top;
if (objs.pixelTop) return objs.pixelTop;
if (obj.offsetTop) return obj.offsetTop;
return 0;
}
function objRight(objectID) {
return objLeft(objectID)+objWidth(objectID);
}
function objBottom(objectID) {
return objTop(objectID)+objHeight(objectID);
}
function objLayer(objectID) {
var objs = xDOM(objectID,1);
if(objs.zIndex) return objs.zIndex;
return 0;
}
function objVisible(objectID) {
var objs = xDOM(objectID,1);
if(objs.visibility == 'hide' || objs.visibility == 'hidden') return 'hidden';
return 'visible';
}

// Cross Browser DOM
// copyright Stephen Chapman, 4th Jan 2005
// you may copy this code but please keep the copyright notice as well
var aDOM = 0, ieDOM = 0, nsDOM = 0; 
var stdDOM = document.getElementById;
if (stdDOM) 
   aDOM = 1; 
else {
     ieDOM = document.all; 
     if (ieDOM) 
        aDOM = 1; 
     else 
     {
      var nsDOM = ((navigator.appName.indexOf('Netscape') != -1) && (parseInt(navigator.appVersion) ==4)); 
      if (nsDOM) aDOM = 1;}
     }
     
function xDOM(objectId, wS) 
{
 if (stdDOM) return wS ? document.getElementById(objectId).style:
 document.getElementById(objectId);
 if (ieDOM) return wS ? document.all[objectId].style: document.all[objectId];
 if (nsDOM) return document.layers[objectId];
}  

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
                
/*
function getScrollerWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
    return (wNoScroll - wScroll);
}
*/
