function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}


function rtrim(stringToTrim) {
	return stringToTrim.replace(/,\s+$/,"");
}

function openForm() {
	grayOut(true);
		
	JSFX_FloatDiv("pop").floatIt();
	$('viewOffer').checked = true;
	$('pop').style.display = 'block';
}

function closeForm(state) {
	if (state) {
		$('viewOffer').checked = true;
		$('offer').value = "true";
	}
	else {
		$('offer').value = "false";
		$('viewOffer').checked = false;
	}
	
	grayOut(false);

	$('pop').style.display = 'none';
} 

function openNews() {
	grayOut(true);
		
	JSFX_FloatDiv("apop").floatIt();
	$('glucoVid').style.display = 'none';
	$('DonovanVid').style.display = 'none';
	$('apop').style.display = 'block';
}

function closeNews() {
	grayOut(false);
	$('glucoVid').style.display = 'block';
	$('DonovanVid').style.display = 'block';
	$('apop').style.display = 'none';
} 

function initOrder() {
	window.onbeforeunload = confirmExit;
}

function confirmExit() {
	setTimeout(floatExit, 500);	
	return 'Click CANCEL to VIEW OUR SPECIAL OFFERS';
}

function floatExit() {
	JSFX_FloatDiv2("exitpop");
}

function validForm() {
	var phone = $("phoneOne").value + $("phoneTwo").value + $("phoneThree").value;
	var result = '';
	if ($("firstName").value == '') { result += "First Name, "; }
	if ($("lastName").value == '') { result += "Last Name, "; }
	if ($("email").value == '') { result += "Email, "; }
	if (phone == '') { result += "Phone Number, "; }
	if ($("address").value == '') { result += "Address, "; }
	if ($("city").value == '') { result += "City, "; }
	if ($("state").selectedIndex == 0) { result += "State, "; }
	if ($("zip").value == '') { result += "Zipcode, "; }
	
	if (result != '') { alert ("Required Fields Missing: " + rtrim(result)); return false; }
	else {

		var value = $("email").value;
		var apos = value.indexOf("@");
		var dotpos = value.lastIndexOf(".");

		if (apos < 1||dotpos-apos < 2) { alert("Invalid E-Mail"); return false; }
		else {
			if (isNaN(phone) || phone.length != 10) { alert("Invalid Phone number"); return false; }
			else {
				var zip = $("zip").value;
				if (isNaN(zip) || zip.length != 5) { alert("Invalid Zipcode"); return false; }
			}
		}
	}
	
	$('pInfo').submit();
}

function validCard() {
	var phone = $("phoneOne").value + $("phoneTwo").value + $("phoneThree").value;
	var result = '';
	if ($("firstName").value == '') { result += "First Name, "; }
	if ($("lastName").value == '') { result += "Last Name, "; }
	if ($("email").value == '') { result += "Email, "; }
	if (phone == '') { result += "Phone Number, "; }
	if ($("address").value == '') { result += "Address, "; }
	if ($("city").value == '') { result += "City, "; }
	if ($("state").selectedIndex == 0) { result += "State, "; }
	if ($("zip").value == '') { result += "Zipcode, "; }
	
	if (result != '') { alert ("Required Fields Missing: " + rtrim(result)); return false; }
	else {

		var value = $("email").value;
		var apos = value.indexOf("@");
		var dotpos = value.lastIndexOf(".");

		if (apos < 1||dotpos-apos < 2) { alert("Invalid E-Mail"); return false; }
		else {
			if (isNaN(phone) || phone.length != 10) { alert("Invalid Phone number"); return false; }
			else {
				var zip = $("zip").value;
				if (isNaN(zip) || zip.length != 5) { alert("Invalid Zipcode"); return false; }
			}
		}
	}
	
	var expMonth = $("expirationmonth").selectedIndex;
	var expYear = $("expirationyear").selectedIndex;
	var cvv = $("cvv").value;
	var cardNum = $("cardNumber").value;
	var terms = $("terms").checked;
	if (expMonth == 0||
		expYear == 0) {
		alert("Invalid Expiration Date");
		return false;
	}
	else {
		if (terms == false) {
			alert("You must agree to the Terms and Conditions");
			return false;
		}
		
		else if (cardNum == '') {
			alert("Invalid Card Number");
			return false;
		}
		else {
			if (cvv == '') {
				alert("Invalid Security Code");
				return false;
			}
			else {
				var isValid = false;
				var ccCheckRegExp = /[^\d ]/;
				isValid = !ccCheckRegExp.test(cardNum);
				if (isValid) {
					var cardNumbersOnly = cardNum.replace(/ /g,"");
					var cardNumberLength = cardNum.length;
					var cardType = $("cardType").value;
					var lengthIsValid = false;
					var prefixIsValid = false;
					var prefixRegExp;

					switch(cardType) {
						case "MC":
						lengthIsValid = (cardNumberLength == 16);
						prefixRegExp = /^5[1-5]/;
						break;

						case "VISA":
						lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
						prefixRegExp = /^4/;
						break;

						default:
						prefixRegExp = /^$/;
						alert("Card type not found");
						return false;
					}

					prefixIsValid = prefixRegExp.test(cardNumbersOnly);
					isValid = prefixIsValid && lengthIsValid;
				}

				if (isValid) {
					var numberProduct;
					var numberProductDigitIndex;
					var checkSumTotal = 0;

					for (digitCounter = cardNumberLength - 1; digitCounter >= 0; digitCounter--) {
						checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
						digitCounter--;
						numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
						for (var productDigitCounter = 0; productDigitCounter < numberProduct.length; productDigitCounter++) {
							checkSumTotal += parseInt(numberProduct.charAt(productDigitCounter));
						}
					}

					isValid = (checkSumTotal % 10 == 0);
				}
				if (isValid == false) { alert("Invalid Card Number"); return false; }
				else { 
					window.onbeforeunload = null; 
					$("orderButton").disabled = true; 
					$("bInfo").submit(); 
					return true;					
				}
			}
		}
	}
}

function autoTab(input,len, e) {
  var isNN = (navigator.appName.indexOf("Netscape")!=-1);
  var keyCode = (isNN) ? e.which : e.keyCode; 
  var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
  if (input.value.length >= len && !containsElement(filter,keyCode)) {
    input.value = input.value.slice(0, len);
    input.form[(getIndex(input)+1) % input.form.length].focus();
  }

  function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
    else
    index++;
    return found;
  }

  function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
  }
  return true;
}

function openTerms() {
	window.open("https://secure.glucothinmd.com/terms.htm", "terms", "menubar=no,width=640,height=480,toolbar=no,scrollbars=yes");
}

function winOpen(what) {
	window.open(what, '', "menubar=no,width=640,height=480,toolbar=no,scrollbars=yes");
}

function checkState() {
	var one = $('optOne').checked;
	var two = $('optTwo').checked;
	var three = $('optThree').checked;
	
	if (three) {
		$('packageOne').style.fontWeight = "normal";
		$('packageTwo').style.fontWeight = "normal";
		$('packageThree').style.fontWeight = "bold";
		$('grandTotal').innerHTML = "$292.35";
		$('onePrice').style.display = "none";
		$('twoPrice').style.display = "none";
		$('threePrice').style.display = "block";
	} else if (two) {
		$('packageOne').style.fontWeight = "normal";
		$('packageTwo').style.fontWeight = "bold";
		$('packageThree').style.fontWeight = "normal";
		$('grandTotal').innerHTML = "$184.65";
		$('onePrice').style.display = "none";
		$('twoPrice').style.display = "block";
		$('threePrice').style.display = "none";
	} else {
		$('packageOne').style.fontWeight = "bold";
		$('packageTwo').style.fontWeight = "normal";
		$('packageThree').style.fontWeight = "normal";
		$('grandTotal').innerHTML = "$4.95";
		$('onePrice').style.display = "block";
		$('twoPrice').style.display = "none";
		$('threePrice').style.display = "none";
	}
}

function checkpState() {
	var state = $('pState').checked;
	
	if (state) {
		$('pOrderForm').style.display = "block";
	} else {
		$('pOrderForm').style.display = "none";
	}
}


function checkShip() {
	var state = $('shipping').selectedIndex;
	if (state == 0) {
		$('sPrice').innerHTML = '$4.95';
		$('tPrice').innerHTML = '$4.95';
	}
	else {
		$('sPrice').innerHTML = '$6.95';
		$('tPrice').innerHTML = '$6.95';
	}
}

function cursorHand() {
	document.body.style.cursor = 'hand';
}

function cursorReset() {
	document.body.style.cursor = 'default';
}

function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+10+'px';
		if (document.body.scrollHeight < 800) { 
			var pageHeight = "800px";
		} else { var pageHeight = document.body.scrollHeight+'px'; }
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
	if (document.body.scrollHeight < 800) { 
		var pageHeight = "800px";
	} else { 
      var pageHeight = document.body.offsetHeight+'px';
	}
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';				 
  } else {
     dark.style.display='none';
  }
}
