// JavaScript Document
function doOnLoad() {
	return true;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function sameAbove () {
  			if (this.form.payment.checked=true) {
				this.form.contactnamepayment.value = this.form.name.value;
				this.form.phonepayment.value = this.form.phone.value;
			}
}

function textCounter(field, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
}

// ********** BEGIN VALIDATION FUNCTIONS ***********
function runValidation() {

		// Add the error messages, if any
	var obj_Error	= new ErrorMsg();
	obj_Error.AddCategory();
	for ( var i = 1; i < ( numChecks + 1 ); i++ )  {
		if ( checkFields[i] != "" ) obj_Error.AddMessage( checkFields[i] );
	}

		// Display errors
	if( obj_Error.errors == false ) {
		document.forms[0].submit();
	} else {
		obj_Error.DisplayMessage();
		return false;
	}
}

// ===== Check if field is required =====
function isRequired ( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	if(( fieldValue == "" ) || ( fieldValue == " " )) {
		errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel + "";
	}
	return errorMsg ;
}

// ===== Validate field minimum and maximum length =====
function validateMinMax ( fieldName, fieldDescription, minLength, maxLength ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	fieldLength	= document.forms[0][fieldName].value.length;
	if ( fieldLength < minLength ) {
		errorMsg = "\"" + fieldDescription +  "\"  - Please enter at least " + minLength + " characters.";
	} else if (( fieldLength > maxLength ) && ( maxLength > 0 )) {
		errorMsg = "\"" + fieldDescription +  "\"  - Please enter less than " + maxLength + " characters.";
	}
	return errorMsg ;
}

// ===== Check if netry contains only valid characters =====
function checkValidChars( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	fieldLength	= document.forms[0][fieldName].value.length;
	for( var i=0; i<fieldLength; i++ ) {
		if ( validChars.indexOf( fieldValue.charAt( i )) == -1 ) {
			errorMsg = "\"" + fieldDescription +  "\" - " + errorLabel + "";
		}
	}
	return errorMsg ;
}

// ===== Check if entry contains entirely identical characters =====
function checkIdentical( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	fieldLength	= document.forms[0][fieldName].value.length;

	if (( fieldLength > 1 ) && ( isComposedOfChars( fieldValue.charAt( 0 ), fieldValue ))) {
		errorMsg = "\"" + fieldDescription +  "\" - " + errorLabel + "";
	}
	return errorMsg ;
}

function isComposedOfChars( curChar, inString ) {
	return ( indexOfFirstNotIn( curChar, inString ) == -1 );
}

function indexOfFirstNotIn( okayChars, inString ) {
	for ( var i=0; i<inString.length; i++ ) {
		if ( okayChars.indexOf( inString.charAt( i )) == -1 ) {
			return i;
		}
	}
	return -1;
}

// ===== Check if entry contains entirely sequential characters =====
function checkSequential( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	fieldLength	= document.forms[0][fieldName].value.length;

	if ( fieldLength > 1 ) {
		for ( var i = 1; i < ( numSeqStr + 1 ); i++ )  {
			if ( strSeq[i].indexOf( fieldValue ) != -1 ) {
				errorMsg = "\"" + fieldDescription +  "\" - " + errorLabel + "";
			}
		}
	}
	return errorMsg ;
}

// ===== Check if an option has been selected =====
function validateSelectBox( fieldName, fieldDescription, errorLabel, checkWhat ) {
	errorMsg	= "";
	optSelected	= document.forms[0][fieldName].selectedIndex;
	fieldValue	= document.forms[0][fieldName].options[optSelected].value;
	if( fieldValue == checkWhat ) {
		errorMsg = "\"" + fieldDescription +  "\" - " + errorLabel + "";
	}
	return errorMsg ;
}

// ===== Check if a checkbox or radio button has been selected =====
function validateBtnsBox( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	selection = null;
	thisButton		= document.forms[0][fieldName];
	for( var i=0; i<thisButton.length; i++ ) {
		if( thisButton[i].checked ) {
		   selection = thisButton[i].value;
		}
	}
	if( selection == null ) {
		errorMsg = "\"" + fieldDescription +  "\" - " + errorLabel + "";
	}
	return errorMsg;
}

// ===== Check if entry contains only numbers =====
function validateNumBox( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	fieldLength	= document.forms[0][fieldName].value.length;

	for( var i = 0; i < fieldLength; i++ ) {
		var ch = fieldValue.substring( i, i + 1 );
		if (( ch < "0" ) || ( ch > "9" )) {
			errorMsg = "\"" + fieldDescription +  "\" - " + errorLabel + "";
		}
	}
	return errorMsg ;
}

// ===== Validate an email address =====
function validateEmailBox ( fieldName, fieldDescription, errorLabel ) {
	errorMsg	= "";
	fieldValue	= document.forms[0][fieldName].value;
	fieldLength	= document.forms[0][fieldName].value.length;

	if ( fieldLength > 0 ) {

		if (( errorLabel == "" ) || ( errorLabel == null )) {

			errorLabel1	= "This is not a valid email address.";			// Not valid
			errorLabel2	= "Missing [ @ ] sign.";						// Missing "@"
			errorLabel3	= "Missing [ . ].";								// Missing "."
			errorLabel4	= "Cannot start with a space.";					// Starts with " "
			errorLabel5	= "Cannot start with [ @ ] sign.";				// Starts with "@"
			errorLabel6	= "Cannot start with [ . ].";					// Starts with "."

			if ( fieldValue.indexOf( "@" ) == -1 ) {
				errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel2 + "";
			} else if ( fieldValue.indexOf( "." ) == -1 ) {
				errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel3 + "";
			} else if ( fieldValue.charAt( 0 ) == " " ) {
				errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel4 + "";
			} else if ( fieldValue.charAt( 0 ) == "@" ) {
				errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel5 + "";
			} else if ( fieldValue.charAt( 0 ) == "." ) {
				errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel6 + "";
			}

		} else {

			if (( fieldValue.indexOf( "@" ) == -1 ) || 					// Missing "@"
				( fieldValue.indexOf( "." ) == -1 ) || 					// Missing "."
				( fieldValue.charAt( 0 ) == "@" ) || 					// Starts with "@"
				( fieldValue.charAt( 0 ) == "." ) 						// Starts with "."
				) {
				errorLabel1	= "This is not a valid email address.";			// Not valid
				errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel1 + "";
			}
		}
	} else if ( fieldValue == "" ) {
		errorLabel1	= "Please enter an email address.";			// Email address missing completely
		errorMsg = "\"" + fieldDescription +  "\"  - " + errorLabel1 + "";
	}
	return errorMsg ;
}
// *********** END VALIDATION FUNCTIONS ************

// ************ BEGIN OBJECT FUNCTIONS *************
function AddCategory( str_Name ) {
		// Creates a new category object at the next space in the array
	this.obj_Errors[this.obj_Errors.length] = new NewCategory( str_Name );
	this.NewCategory = NewCategory;
}

function NewCategory( str_Name) {
		//  Initializes the category values
	this.str_Name		= str_Name;
	this.str_Error		= "";
}

function AddMessage( str_Msg ) {
	for ( var i = 0; i < this.obj_Errors.length; i++ )  {
		this.obj_Errors[i].str_Error += errorBullet;
		this.obj_Errors[i].str_Error += str_Msg + "\n";
		this.errors = true;
		return true;
	}
}

function ErrorMsg() {
		//  This is the object you create to keep track of errors in the document
	this.obj_Errors		= new Array();
	this.errors			= false;
	this.AddCategory	= AddCategory;
	this.AddMessage		= AddMessage;
	this.DisplayMessage	= DisplayMessage;
}
// ************* END OBJECT FUNCTIONS **************

function DisplayMessage() {
		// Displays the error messages.
		// If none, false is returned and no message is displayed.
	if ( this.errors == false ) {
		return false;
	} else {
		var str_msg = "";
		str_msg += errorLine1 + "\n";
		str_msg += errorLine2 + "\n";
		for ( var i = 0; i < this.obj_Errors.length; i++ ) {			// Go through all of the objects
			if ( this.obj_Errors[i].str_Error != '' ) {					// If errors, write the errors
				str_msg += "\n" + errorLine3 + "\n";
				str_msg += this.obj_Errors[i].str_Error + "\n";
			}
		}
		alert( str_msg );												// Display the error message
		return true;
	}
}

/* Special JavaScript function for creating new windows and 
   and spooling the data to that window for processing 
   Taken from JavaScript Central
*/

function createTarget(form) {
	endTarget = form.target;
	theColon = endTarget.indexOf(":");

	if (theColon != -1) {
		form.target = endTarget.substring(0,theColon);
		form.args = endTarget.substring(theColon+1);
	} else if(typeof(form.args)=="undefined") {
		form.args = "";
	}

	if (form.args.indexOf("{")!=-1) {
		theArgs = form.args.split("{");
		form.args = theArgs[0];
		
		for (var i = 1; i < theArgs.length;i++) {
			theArgs[i] = theArgs[i].split("}");
			form.args += eval(theArgs[i][0]) + theArgs[i][1];
		}
	}

	form.args = form.args.replace(/ /g,"");
	newWin = window.open('',form.target,form.args);

	if(typeof(focus)=="function")
		newWin.focus();
	
	return true;
}

// this function sets up the onmouseover/onmouseout events
// to do the highlighting when appropriate
// the styles are defined in the stylesheet

function highlightRows() {
	var trs,i;
	trs=document.getElementsByTagName('tr');

	for (i=0; i< trs.length; i++) {
		if (trs[i].className == 'highlightedtr') {
			trs[i].onmouseover=function(){highlight(this,1);}
			trs[i].onmouseout=function(){highlight(this,0);}
		}
	}
}

// this function actually does the highlighting
function highlight(o,state) {
	o.className=state==1?'highlight':'normal';
}

// this function gives a confirmation message before downloading process begins
	function ShowAlert(popupwindow){
		var agree=confirm("Your download is being gathered.  Small downloads will take only a few seconds however large downloads may take upwards of 15 minutes to prepare during which nothing will appear to be happening.  Please be patient.  You will be notified on screen when your download is ready.\n\nIf you encounter problems downloading files from our site (e.g. if downloads fail to complete or you experience connection problems), we highly recommend installing a download manager program that will help download large files by automatically resuming broken downloads.  A list of free download managers can be viewed on Wikipedia.");
		if (agree) {
		    window.open('',popupwindow,'width=400,height=475,scrollbars,resizable');
       		return true;
       		}
		else
		{
        	return false;
        	}
}

	function ShowAlertBrowse(urllocation){
		var agree=confirm("Your download is being gathered.  Small downloads will take only a few seconds however large downloads may take upwards of 15 minutes to prepare during which nothing will appear to be happening.  Please be patient.  You will be notified on screen when your download is ready.\n\nIf you encounter problems downloading files from our site (e.g. if downloads fail to complete or you experience connection problems), we highly recommend installing a download manager program that will help download large files by automatically resuming broken downloads.  A list of free download managers can be viewed on Wikipedia.");
		if (agree) {
		    window.open(urllocation,'download','width=400,height=525,scrollbars,resizable');
       		return true;
   	}
		else
		{
        	return false;
   	}
}

	function ShowAlertBrowseC(){
		var agree=confirm("Your download is being gathered.  Small downloads will take only a few seconds however large downloads may take upwards of 15 minutes to prepare during which nothing will appear to be happening.  Please be patient.  You will be notified on screen when your download is ready.\n\nIf you encounter problems downloading files from our site (e.g. if downloads fail to complete or you experience connection problems), we highly recommend installing a download manager program that will help download large files by automatically resuming broken downloads.  A list of free download managers can be viewed on Wikipedia.");
		if (agree) {
       		return true;
 		}
		else
		{
        	return false;
   	}
}

// function to insert message and button for closing JavaScript window or 
// going back.  Used primarily in templates/ pages.
function insertCloseWindowCode() {
	document.write('<p>');
	if (window.opener != null) {
		document.write('<a href="javascript:window.close();" title="Close this window">');
		document.write('<img src="/graphics/but_close.jpg" alt="[ Close ]" width="80" height="25" border="0"></a>');
	}
	else {
		if (((/MSIE (\d+\.\d+);/.test(navigator.userAgent)) && (history.length > 0)) || (history.length > 1)) {
			// Internet Explorer (and so does Opera but who cares) counts
			// history starting at 0 while Firefox, Chrome, and Safari start
			// the count at 1.
			document.write('[ <a href="javascript:history.back();" title="Go back">Back</a> ]');
		}
	}
	document.write('</p>');
}

// function to reload the calling window and handle the case when the domain
// differs. 
function reloadParent() {
	try {
		window.opener.location.reload();
	} catch (err) {
		// Error expected if opener is in GoMap domain.
	}
}

// function to focus JS window if this window opened by 
// JS function and window named something specific.
function windowFocusByName(winName) {
	if ((window.opener != null) && (window.name==winName)) {
		window.focus();		
		try {
			// Try to reload the parent window.
			window.opener.location = window.opener.location;		
		} catch (err) {
			// This script is in the gateway domain and is being called from the
			// ntgomap domain so the attempt to access the properties above is
			// failing. (The opener is in another domain) Given that we know that
			// we are being called from GoMap, the alternative is to do nothing
			// in this case.
		}
	}
	// self.resizeTo(400,400);
}

// function to focus JS window if this window opened by 
// JS function
function windowFocus() {
	if (window.opener != null) {
		window.focus();
	}
}

// dynamically update an HTML fragment on the page
// using the W3C DOM
// Rey Nunez, CodingForums helper.
function changeContentByDOM(elementid,content) {
	var el, rng, htmlFrag;

	// check for W3C standard browsers
	if (document.getElementById && !document.all) {
		rng = document.createRange();
		el = document.getElementById(elementid);
		rng.setStartBefore(el);
		htmlFrag = rng.createContextualFragment(content);

		while (el.hasChildNodes()) {
			el.removeChild(el.lastChild);
		}
		
		el.appendChild(htmlFrag);
	// cater to IE 5/6
	} else if (document.all && document.getElementById) {
		el = document.getElementById(elementid);
		el.innerHTML = content;
	}
}

// given a number, format it properly as a dollar 
// value with a leading 0 if necessary, a decimal point, 
// and two decimal places.
// Used primarily in adminorderdetail.php
function formatDollarValue(n) {
	var Bstr = "";
	var b = n * 100;
	var c = Math.round(b);
	var Astr = c.toString();
	var Alength = Astr.length;
	
	// handle values under 1.00
	if (Alength == 1) {
		Bstr = Bstr + '0.0';
	} else if (Alength == 2) {
		Bstr = Bstr + '0.';
	}
	
	var dot = Alength - 3;
	var counter = 0;
	
	while (counter < Alength ) {
		Bstr = Bstr + Astr.charAt(counter);
		if (counter == dot) Bstr = Bstr + ".";
		counter = counter + 1;
	}

	var d = Bstr;
	return d;
	
}

// forcing link in a pop-up window to open the URL 
// from the window that opened it
function loadit(url) {
	if (top.opener && !top.opener.closed) {
	 top.opener.location = url;
	 top.opener.focus();
	}
	else open(url,'mainwin');
	// self.close(); //optional
	return false;
}

function loadCart() {
	try {
		// Test access to properties of the window.opener and then
		// try to load the cart in the opener.
		if (window.opener.location.href) {
			window.opener.location.href = 'cart.php';
			self.close();		
		}
	} catch (err) {
		// This script is in the gateway domain and is being called from the
		// ntgomap domain so the attempt to access the properties above is
		// failing. (The opener is in another domain) Given that we know that
		// we are being called from GoMap, load the cart in the current window.    
		location.href = 'cart.php';
	}
}
