﻿/*
The SoftAd Group
Copyright (c) 2000-2004 The SoftAd Group, Inc.  All rights reserved
*/
// Generic Javascript Library for ChannelNet processing
// Copyright © 1999-2001 SoftAd Group, Inc.

// for variables used in place of text alerts (i.e. CNVALIDERROR2), see en-us.js, de-de.js, etc.

var REGEXP_ANYVALUE_REQUIRED = '^.+$';
var REGEXP_FIRSTNAME_REQUIRED = '^[a-zA-Z ]+$';
var REGEXP_FIRSTNAME_OPTIONAL = '^[a-zA-Z ]*$';
var REGEXP_INITIAL_REQUIRED = '^[a-zA-Z]$';
var REGEXP_INITIAL_OPTIONAL = '^[a-zA-Z]?$';
var REGEXP_LASTNAME_REQUIRED = '^[a-zA-Z \\.\\-,\']+$';
var REGEXP_LASTNAME_OPTIONAL = '^[a-zA-Z \\.\\-,\']*$';
var REGEXP_CITY_REQUIRED = '^[a-zA-Z \\.\\-,\']+$';
var REGEXP_CITY_OPTIONAL = '^[a-zA-Z \\.\\-,\']*$';
var REGEXP_PHONENUMBER_REQUIRED = '^[\\w()\\-. +]{1,20}$';
var REGEXP_PHONENUMBER_OPTIONAL = '^[\\w()\\-. +]{0,20}$';
var REGEXP_POSTALCODE_REQUIRED = '^[\\w \\-\\.]{1,13}$';
var REGEXP_POSTALCODE_OPTIONAL = '^[\\w \\-\\.]{0,13}$';
var REGEXP_EMAIL_REQUIRED = '^(.+@.+\\.[a-zA-Z]+)$';
var REGEXP_EMAIL_OPTIONAL = '^(.+@.+\\.[a-zA-Z]+)?$';
var REGEXP_STATE_REQUIRED = '^[A-Za-z]{2,2}$';

var previousFieldName;		// string name of the field which was previously validated
var imgs = new Array();      // array of the images on a page which are highlighted on a mouseover
var wasSubmitted = false;   // boolean used to determine if the page has already been submitted

// -------------------------------------------------------------------------------
// Function         : handleCNError(strErrMsg)
// -------------------------------------------------------------------------------
// This function displays a ChannelNet Error message
// -------------------------------------------------------------------------------
// Returns a boolean.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME           TYPE      DESCRIPTION
// strErrMsg      string    The text to display for the error
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function handleCNError(strErrMsg) {
    var strEntireMsg = CNVALIDERROR0 + '\n' + '\n';
    
    if(strErrMsg) {
		strEntireMsg += strErrMsg;
	}
	
    alert(strEntireMsg);
}

// -------------------------------------------------------------------------------
// Function         : formHandler(formObj, strMessageText, escapeStrings)
// -------------------------------------------------------------------------------
// This function concatenates all of the channelnet information which
// is required for the criteria string in the crt element of the form and makes
// sure that all of the required form fields exist.
// NOTE: THIS SHOULD BE CALLED AS FOLLOWS
// <form method="post" onsubmit="return formHandler(this)">
// if the return is omitted form submission won't be canceled when an
// error occurs
// -------------------------------------------------------------------------------
// Returns true if the form passes all validation and false if it doesn't.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME           TYPE      DESCRIPTION
// formObj        form      Reference to the form which is being submitted.
//                            formObj should always be this.
// strMessageText string    The text to dispaly if the form hasn't changed
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function formHandler(formObj, strMessageText, escapeStrings)
{

	var elementName;				// the name of a form element
	var elementIndex;				// index of the element in the form
	var optionIndex;				// index of the option in a select box
	var elementValue;				// value for a form element
	var formLength;
	var currentElement;
	var criteriaValue;
	var returnValue = true;
	//alert('');
	// checks to make sure the form wasn't already submitted
	if(wasSubmitted) {
		//handleCNError(CNSUBMITERROR1 + '\n' + CNSUBMITERROR2);
		returnValue = false;
	} else {
	
		// checks to see if anything has changed on the form, if not submission is cancelled
		if (!hasFormChanged(formObj)) {
	
			// set the default message
			if (!strMessageText || strMessageText == '') {
				strMessageText = CNHASCHANGEDERROR;
			}
			
			// displays an error
			handleCNError(strMessageText);
			returnValue = false;
			
		} else {
	
			// stops the form submission if the required elements and element values
			// aren't included in the form
			if (!formObj.cn) {
				handleCNError(CNGRAMMARRULESERROR1 + '\n' + CNGRAMMARRULESERROR2);
				returnValue = false;
			} else if (formObj.cn.value=='') {
				handleCNError(CNGRAMMARRULESERROR1 + '\n' + CNGRAMMARRULESERROR3);
				returnValue = false;
			} else if (!formObj.act) {
				handleCNError(CNGRAMMARRULESERROR1 + '\n'  + CNGRAMMARRULESERROR4);
				returnValue = false;
			} else if (formObj.act.value=='') {
				handleCNError(CNGRAMMARRULESERROR1 + '\n' + CNGRAMMARRULESERROR5);
				returnValue = false;
			} else if (!formObj.debug) {
				handleCNError(CNGRAMMARRULESERROR1 + '\n' + CNGRAMMARRULESERROR6);
				returnValue = false;
			} else if (formObj.debug.value!='0' && formObj.debug.value!='1' && formObj.debug.value!='2' && formObj.debug.value!='3') {
				handleCNError(CNGRAMMARRULESERROR1 + '\n' + CNGRAMMARRULESERROR7);
				returnValue = false;
			} else if (!formObj.crt) {
				handleCNError(CNGRAMMARRULESERROR1 + '\n' + CNGRAMMARRULESERROR8);
				returnValue = false;
			} else {
	
				// initializes the criteria string value
				criteriaValue='';
				
				previousFieldName = '';

				formLength = formObj.elements.length;
				
				// loops through the elements of the form and adds them to the crt
				for(elementIndex=0; elementIndex < formLength; elementIndex++){
					
					currentElement = formObj.elements[elementIndex];
					elementName = currentElement.name;
					
					// calls the onchange event for every element on the form
					if (!currentElement.disabled && currentElement.type!="hidden" && elementName != previousFieldName && currentElement.onchange && currentElement.onchange!="") {
						if (!currentElement.onchange()) {
							returnValue = false;
							break;
						}
					}
					
					// doesn't add the cn, act, debug, style, channel, and crt elements to the crt value
					// also excludes empty elements
					if (currentElement.value!="" && elementName!="act" && elementName!="cn" && elementName!="crt" && elementName!="debug" && elementName!="style" && elementName!="channel" && currentElement.type) {
						// ignores form elements that have a name that begins
						// with an underscore(_)
						if (elementName.charAt(0)!='_') {
							
							var elementValue = '';
							
							switch (currentElement.type) {
								case "select-multiple":						
									
									var optionLength = currentElement.options.length;
									
									for (optionIndex=0;optionIndex<optionsLength;optionIndex++) {
										var currentOption = currentElement.options[optionIndex];
										if (currentOption.selected) {
										
											if (elementValue!='') {
												elementValue = Trim(elementValue) + "|"
											}

											elementValue = elementValue + currentOption.value;
										}
									}
									
									break;
									
								case "select-one":
								
									elementValue = currentElement.options[currentElement.selectedIndex].value;
									break;
									
								case "radio": case "checkbox":
									
									if (currentElement.checked) {
										elementValue = currentElement.value;
									}
									break;
									
								default:
								
									elementValue = currentElement.value;
									break;
									
							}
							
							if (escapeStrings) {
								elementValue = escapeValues(elementValue);
							}
							
							criteriaValue = appendParameter(criteriaValue, elementName, elementValue);
							
						}
					}
				}
				
				formObj.crt.value = criteriaValue;

			}
		}
		
		if(returnValue) {
			wasSubmitted = true;
		}
	}
	
	//alert("Criteria: " + formObj.crt.value);
	// alert("Return Value: " + returnValue);
	return returnValue;
}

// -------------------------------------------------------------------------------
// Function         : appendParameter(strCriteria, strName, strValue)
// -------------------------------------------------------------------------------
// This function appends a parameter to the criteria string
// -------------------------------------------------------------------------------
// Returns a string containing the parameter appended to the criteria string.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME           TYPE      DESCRIPTION
// strCriteria    string    The criteria string
// strName        string    The name of the parameter
// strValue       string    The value of the parameter
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function appendParameter(strCriteria, strName, strValue) {

	strValue = Trim(strValue);
	
	if(strValue && strValue!='') {
	
		// places an ampersand(&) between form elements
		if (strCriteria && strCriteria!='') {
			strCriteria = strCriteria + "&";
		}
	
		strCriteria = strCriteria + Trim(strName) + "=" + strValue;
	}
			
	return strCriteria;	
					
}

// -------------------------------------------------------------------------------
// Function         : escapeValues(stringToEscape)
// -------------------------------------------------------------------------------
// This function escapes special characters in a string
// -------------------------------------------------------------------------------
// Returns a string with the special characters escaped.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME           TYPE      DESCRIPTION
// strintToEscape string    A string containing special characters
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function escapeValues(stringToEscape) {

	var regExp = /&\w+=(.+)/g
	
	// doesn't escape the string if it contains name=value pairs separated by
	//    ampersands such as a criteria string
	if(stringToEscape.search(regExp)==-1) {
	
		// escapes the string if it doesn't contain any name/value pairs
		stringToEscape = escape(stringToEscape);
		
	}
	
	return stringToEscape;
}

// -------------------------------------------------------------------------------
// Function         : validate(formElement, regExpText, errorMsg)
// -------------------------------------------------------------------------------
// This function validates the data entered into a form element using regular
// expressions and returns an user specified error if the value of the element
// doesn't match the regular expression.
// -------------------------------------------------------------------------------
// Returns true if the form element passes validation and false if it doesn't.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formElement	element		Then form element which will have its value validated.
// regExpText	string		The regular expression to validate the element with.
// errorMsg		string		The message to display if the value of the form
//							element isn't valid.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function validate(formElement, regExpText, errorMsg)
{

	var regExpObj = new RegExp(regExpText,'');
	var returnValue = true;

	if (!errorMsg) {
		errorMsg = '';
	}
	
	if (previousFieldName!=formElement.name) {
		// checks to see if the field value matches the regular expression
		var elementValue = (formElement.type == 'select-one' ? formElement.options[formElement.selectedIndex].value : formElement.value);
		if (!regExpObj.test(Trim(elementValue))) {

			// displays an error message
			handleCNError(CNVALIDERROR1 + '\n' + CNINVALIDVALUEERROR + '\n' + errorMsg);

			// selects the field value
			if (formElement.focus) {
				formElement.focus();
			}
			if(formElement.select) {
				formElement.select();
			}
		
			previousFieldName = formElement.name;
			returnValue = false;
		} else {
			returnValue = true;
		}
	}

	return returnValue;

}


// -------------------------------------------------------------------------------
// Function         : concatFields(formElement)
// -------------------------------------------------------------------------------
// Author           : Chad Peck
// Created on       : Friday, March 24, 2000
// 
// This function takes the values of textboxes which have identical names
// and concatenates the values which are separated by a bar(|)
// the the resulting values is stored in a hidden field.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formElement	element		The form element which calls this function.  It should
//							always be this.
// -------------------------------------------------------------------------------
// Last Updated     : 
// Updated by       : 
// -------------------------------------------------------------------------------

function concatFields(formElement) {

	var elementIndex;
	var concatValue = '';
	var elementName = formElement.name;
	
	// loops through all of the elements that have the same name as the
	// one that called this function
	
	for(elementIndex=0;elementIndex<formElement.form.elements[elementName].length;elementIndex++) {
		
		if (formElement.form.elements[elementName][elementIndex].value!=null && formElement.form.elements[elementName][elementIndex].value!="") {
			// concatenates the values
			concatValue = concatValue + formElement.form.elements[elementName][elementIndex].value + '|';
		}
	}
	
	// removes the last bar(|)
	concatValue = concatValue.substring(0,concatValue.length-1);
	
	// takes the underscore off of the name
	elementName = elementName.substring(1,elementName.length);
	
	// stores the value a hidden field of the same name
	formElement.form.elements[elementName].value = concatValue;

}



// -------------------------------------------------------------------------------
// Function         : focusOnFirstField()
// -------------------------------------------------------------------------------
// This function gives focus to the first form element which can receive focus on
// a page.  If the field can be selected then it is.
// -------------------------------------------------------------------------------
// Returns true if focus is set to the first field and false if it isn't.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function focusOnFirstField() {

	var formIndex;
	var numOfForms = document.forms.length;
	var elementIndex;
	var returnValue;

	for(formIndex=0; formIndex < numOfForms; formIndex++) {

		var currentForm = document.forms[formIndex];
		var formLength = currentForm.length;
		
		for(elementIndex=0; elementIndex < formLength; elementIndex++) {

			var currentElement = currentForm.elements[elementIndex];
			var elementType = currentElement.type;
			
			// finds the first element which accepts focus
			if (elementType=="text" || elementType=="textarea" || elementType=="password" || elementType=="file" || elementType == "select-one") {
				
				if(currentElement.focus && !currentElement.disabled && !isElementHidden(currentElement)) {
					currentElement.focus();
					if (currentElement.select) {
						currentElement.select();
					}
					returnValue = true;
					break;
				}
			}
		}	
	}
	
	return returnValue;
}

function isElementHidden(currentElement) {
	var hidden = false;
	if(currentElement) {
		currentNode = currentElement.parentNode;
		while(currentNode) {
			if((currentNode.visibility && currentNode.visibility == 'hide') || (currentNode.style && (currentNode.style.visibility && currentNode.style.visibility == 'hidden') || (currentNode.style.display && currentNode.style.display == 'none'))) {
				hidden = true;
				break;
			}
			if(currentNode.tagName && currentNode.tagName.toUpperCase() == "HTML") break;
			currentNode = currentNode.parentNode;
		}
	}
	return hidden;		
}


// -------------------------------------------------------------------------------
// Function         : canProceed(formObj)
// -------------------------------------------------------------------------------
// Author           : Chad Peck
// Created on       : Monday, March 27, 2000
// 
// This function is called from the onclick event handler of a link to determine
// if changes have been made to the form specified by formObj and to see if the
// user wants to proceed the link.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formObj		form		Reference to a form object. This is the form which
//							should be reset.  If the form is contained in a layer
//							then it	must be called referenced from within the 
//							layer.
// -------------------------------------------------------------------------------
// Last Updated     : 
// Updated by       : 
// -------------------------------------------------------------------------------

function canProceed(formObj) {

	// checks to see if the form has changed
	if (hasFormChanged(formObj)) {
	
		// prompts the user to proceed
			
		if (confirm("You have made changes to the form on this page without saving. Continue?")) {
			return true;
		} else {
			return false;
		}
	
	} else {
		return true;
	}
}

// -------------------------------------------------------------------------------
// Function         : hasFormChanged(formObj)
// -------------------------------------------------------------------------------
// This function checks all of the elements in a form to determine if they have
// changed from the default values which were set in the HTML.  It returns a
// boolean value.
// -------------------------------------------------------------------------------
// Returns true if the value of any form element has change, false otherwise
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formObj		form		Reference to a form object.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function hasFormChanged(formObj) {

	var elementIndex;
	var optionIndex;
	var returnValue = false;
	var undefined;
	
	if (formObj) {
	        if (formObj._dontValidate != null)
			return true;
		var formLength = formObj.elements.length;

		// checks all of the form elements to see if the values have changed
		for(elementIndex=0; elementIndex < formLength; elementIndex++) {
		
			var currentElement = formObj.elements[elementIndex];
			var elementType = currentElement.type;
			
			if ((currentElement.name=="_noinput") && (currentElement.value=="1")) {
				return true;
			} else if (elementType=="hidden") {
				if (currentElement.defaultValue!=undefined && currentElement.value!=currentElement.defaultValue) {
					returnValue = true;
					break;
				}
			} else if (elementType=="text" || elementType=="textarea" || elementType=="password" || elementType=="file") {
				if (currentElement.value!=currentElement.defaultValue) {
					returnValue = true;
					break;
				}
			} else if (elementType=="checkbox" || elementType=="radio") {
				if (currentElement.checked!=currentElement.defaultChecked) {
					returnValue = true;
					break;
				}
			} else if (elementType=="select-one" || elementType=="select-multiple") {
				
				var optionsLength = currentElement.options.length;
				
				for (optionIndex=0; optionIndex < optionsLength; optionIndex++) {
				
					var currentOption = currentElement.options[optionIndex];
					
					if (currentOption.defaultSelected!=currentOption.selected) {
						returnValue = true;
						break;
					}
				}
			}
	
		}
	}

	//alert("hasFormChanged() : " + returnValue);
	return returnValue;
}

// -------------------------------------------------------------------------------
// Function         : canDelete()
// -------------------------------------------------------------------------------
// This function prompts the user to make sure that they want to delete the
// selected item.
// -------------------------------------------------------------------------------
// Returns true if the value of any form element has change, false otherwise
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function canDelete() {

	// prompts the user to confirm deletion
	if (confirm(CNDELETEPROMPT)) {
		return true;
	} else {
		return false;
	}
}

// -------------------------------------------------------------------------------
// Function         : imagesToSwap(plainImage, highlightedImage)
// -------------------------------------------------------------------------------
// This function creates two images: a plain one and one that is highlighted on a
// mouseover event.
// -------------------------------------------------------------------------------
// Returns true if the imgs array exist, false otherwise
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// plainImage       string		The name of the original image.
// highlightedImage	string		The name of the image to use when the onmouseover
//								event occurs.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function imagesToSwap(plainImage, highlightedImage) {
	
	var returnValue = false;
	
	if(this) {
		
		returnValue = true;
		
		this.plain = new Image();
		this.plain.src = plainImage;
	
		this.highlighted = new Image();
		this.highlighted.src = highlightedImage;
	}

	return returnValue;

}

// -------------------------------------------------------------------------------
// Function         : preloadImages(imagesArray)
// -------------------------------------------------------------------------------
// This function preload images into memory which will be used for mouseover
// events.
// -------------------------------------------------------------------------------
// Returns true if there are images to load and there is an imgs array,
//     false otherwise
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// imagesArray		array		This is an array of the names of all of the images
//								which will be highlighted by mouseover events. 
//								This array contains only the original (plain)
//								 images.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function preloadImages(imagesArray)
{

	var imgIndex;
	var highlightedImage;
	var returnValue = false;

	if (imagesArray && imgs) {
		
		returnValue = true;
		
		var arrayLength = imagesArray.length;
		
		for(imgIndex=0; imgIndex<arrayLength; imgIndex++) {
	
			highlightedImage = imagesArray[imgIndex];
			if(highlightedImage.lastIndexOf('.') >0){
				highlightedImage = highlightedImage.substring(0,highlightedImage.lastIndexOf('.')) + '-m' + highlightedImage.substring(highlightedImage.lastIndexOf('.'),highlightedImage.length);
				imgs[imgs.length] = new imagesToSwap(imagesArray[imgIndex],highlightedImage);
			}
			
		}
	}
	
	return returnValue;
}

// -------------------------------------------------------------------------------
// Function         : highlightImage(imgSource)
// -------------------------------------------------------------------------------
// This function changes the src of an Image whenever a mouseover event fires.
// -------------------------------------------------------------------------------
// Returns true if the image is in the array, false otherwise
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// imgSource		img			This is the image object in the HTML which will
//								have its src replaced.  imgSource should always be
//								referenced with this.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function highlightImage(imgSource)
{

	var returnValue = false;
	
	if(imgs && imgs.length) {
	
		// loops through the imgs array to find the image
		for(i=0;i<imgs.length;i++) {
		if (imgSource.src.toUpperCase()==imgs[i].plain.src.toUpperCase()) {
				imgSource.src=imgs[i].highlighted.src;
				returnValue = true;
				break;
			}
		}
	}
	
	return returnValue;
}

// -------------------------------------------------------------------------------
// Function         : unhighlightImage(imgSource)
// -------------------------------------------------------------------------------
// This function changes the src of an Image back to the plain version whenever
// a mouseover event fires.
// -------------------------------------------------------------------------------
// Returns true if the image is in the array, false otherwise
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// imgSource		img			This is the image object in the HTML which will
//								have its src replaced.  imgSource should always be
//								referenced with this.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function unhighlightImage(imgSource)
{
	var returnValue = false;
	
	if(imgs && imgs.length) {
	
		// loops through the imgs array to find the image
		for(i=0;i<imgs.length;i++) {
			if (imgSource.src.toUpperCase()==imgs[i].highlighted.src.toUpperCase()) {
				imgSource.src=imgs[i].plain.src;
				returnValue = true;
				break;
			}
		}
	}

	return returnValue;
}

// -------------------------------------------------------------------------------
// Function         : LTrim(str)
// -------------------------------------------------------------------------------
// This function removes spaces from the beginning of a string.
// -------------------------------------------------------------------------------
// Returns the trimmed string
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// str              string      The string to remove spaces from.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function LTrim(str) {

	if(str) {
		str = str.replace(/^\s+/g,"");
	} else {
		str = '';
	}
	
	return str;
}

// -------------------------------------------------------------------------------
// Function         : RTrim(str)
// -------------------------------------------------------------------------------
// This function removes spaces from the end of a string.
// -------------------------------------------------------------------------------
// Returns the trimmed string
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// str              string      The string to remove spaces from.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function RTrim(str) {

	if(str) {
		str = str.replace(/\s+$/g,"");
	} else {
		str = '';
	}
	
	return str;
}

// -------------------------------------------------------------------------------
// Function         : Trim(str)
// -------------------------------------------------------------------------------
// This function removes spaces from the beginning and end of a string.
// -------------------------------------------------------------------------------
// Returns the trimmed string
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// str              string      The string to remove spaces from.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function Trim(str) {
	return RTrim(LTrim(str));
}

// -------------------------------------------------------------------------------
// Function         : cnReplace(strSource, strReplace, strWith)
// -------------------------------------------------------------------------------
// This function replaces occurrences of a substring strReplace with another string
// strWith in a sting strSource.
// -------------------------------------------------------------------------------
// Returns the string with the replacement
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// strSource        string      The string to containing a substring to be replaced
// strReplace       string      The substring to replace.
// strWith          string      The substring to make the replacement with.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function cnReplace(strSource, strReplace, strWith) {

	if(strSource) {
		strSource = strSource.replace(strReplace, strWith);
	} else {
		strSource = '';
	}
	
	return strSource;
	
}

// -------------------------------------------------------------------------------
// Function         : urlencode_internal(sIn)
// -------------------------------------------------------------------------------
// This function encodes a string to send in a URL using the supplied translation
// table.
// -------------------------------------------------------------------------------
// Returns a URL encoded string.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME							TYPE        DESCRIPTION
// szIn							String      The plaintext for encoding
// sURLEncodedChars             String      The target character encodings
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 10/10/2000   Dan Boresjo Created

function urlencode_internal(sIn, sURLEncodedChars){
   var LenStr = sIn.length;
   var sOut = "";
   var sReplace = "";
   var sURLChars = " ,~,!,#,$,%,^,&,(,),+,=,[,{,],},\,|,`,',:,;,/,<,>";
   var aURLChars = sURLChars.split(",");
   var aURLEncodedChars = sURLEncodedChars.split(",");

   if (LenStr > 0) {
     for (Count=0; Count<=LenStr; Count++) {
        StrChar = sIn.substring(Count, Count+1);
        for (j=0; j<=25; j++) {
           if (StrChar==aURLChars[j]) {
             sReplace = aURLEncodedChars[j];
           } 
        }
        if (sReplace != "") {
          sOut = sOut + sReplace;
          sReplace="";
        } else {
          sOut = sOut + StrChar;
        }
     }
  }
  else {
    return sIn;
  }
  return(sOut.substring(0, sOut.length-3));
}

// -------------------------------------------------------------------------------
// Function         : urlencode(sIn)
// -------------------------------------------------------------------------------
// This function encodes a string to send in a URL.
// -------------------------------------------------------------------------------
// Returns a URL encoded string.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME							TYPE        DESCRIPTION
// sIn							String      The plaintext for encoding
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 10/10/2000   Dan Boresjo Created

function urlencode(sIn){
   var sURLEncodedChars = "+,%7E,%21,%23,%24,%25,%5E,%26,%28,%29,%2B,%3D,%5B,%7B,%5D,%7D,%5C,%7C,%60,%27,%3A,%3B,%2F,%3C,%3E";
   return urlencode_internal(sIn, sURLEncodedChars);
}

// -------------------------------------------------------------------------------
// Function         : urlencode_field(sIn)
// -------------------------------------------------------------------------------
// This function encodes a string to send in a URL, including double-encoding of
// ampersands so that they pass through the responseloop correctly.
// -------------------------------------------------------------------------------
// Returns a URL encoded string.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME							TYPE        DESCRIPTION
// sIn							String      The plaintext for encoding
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 10/10/2000   Dan Boresjo Created

function urlencode_field(sIn){
   /*var sURLEncodedChars = "+,%7E,%21,%23,%24,%25,%5E,%25%32%36,%28,%29,%2B,%3D,%5B,%7B,%5D,%7D,%5C,%7C,%60,%27,%3A,%3B,%2F,%3C,%3E";
   return urlencode_internal(sIn, sURLEncodedChars);*/
   return escape(sIn);
}

// -------------------------------------------------------------------------------
// Function         : PopupWindow (myLocation, scroll, width, height, windowName)
// -------------------------------------------------------------------------------
// This function opens a new window with no menus or toolbars using the file
// specified by myLocation.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// myLocation	string		The name of the file/URL to open in the window.
// scroll		boolean		Will scrollbars appear on the window.
// width		integer		Width of the window in pixels.
// height		integer		Height of the window in pixels.
// windowName	string		Name of the window.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 03/24/2000   Chad Peck   Created

function PopupWindow (myLocation, scroll, width, height, windowName) {
	var oWin;
	if (!windowName) {
		windowName = 'newWin';
	}
	
	if (/channelnet.aspx/i.test(myLocation)) {
		myLocation = myLocation + "&lang=" + CNLANGNAME;
	}
	
	oWin = window.open(myLocation, windowName,'menubar=0,toolbar=0,location=0,directories=0,status=0,scrollbars=' + scroll + ',resizable=yes,width=' + width + ',height=' + height);
	oWin.focus();
	
}

// -------------------------------------------------------------------------------
// Function         : isValidDate(day, month, year)
// -------------------------------------------------------------------------------
// Returns nulliff the given parameters correspond to a valid date or an
// appropriate error message if they don't.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// day          integer     The day of the month
// month        integer     The month
// year         integer     The year
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME             DESCRIPTION
// 03/24/2000   George Pollard   Created
// 10/25/2000   George Pollard   Updated

function isValidDate(day, month, year) {
	var len = 0;
	month = parseInt(month, 10);
	day = parseInt(day, 10);
	if ((month<1)||(month>12))
		return month+" is not a valid month.";
	
	// A leap year occurs every four years except for those multiples of 100 which are not also multiples of 400.
	// eg 1600, 2000 and 2400 are leap years but 1700, 1800, 1900 and 2100 etc are not
	var isLeap = ( ((year%4)==0) && ((year%100)!=0) ) || ((year%400)==0);
	if (month==1) len=31; // jan
	if ((month==2)&&!isLeap) len=28; // feb (non-leap year)
	if ((month==2)&&isLeap) len=29;  // feb (leap year)
	if (month==3) len=31; // mar
	if (month==4) len=30; // apr
	if (month==5) len=31; // may
	if (month==6) len=30; // jun
	if (month==7) len=31; // jul
	if (month==8) len=31; // aug
	if (month==9) len=30; // sep
	if (month==10) len=31; // oct
	if (month==11) len=30; // nov
	if (month==12) len=31; // dec
	
	if ((day<1)||(day>len)) {
		if ((day==29)&&(month==2))
			return year + " is not a leap year.";
		if ((day>0)&&(day<32))
			return day + " is not a valid day for month " + month + ".";
		return day + " is not a valid day of the month.";
	}
	
	return null;
}

// -------------------------------------------------------------------------------
// Function         : getDateTicks(ctrl)
// -------------------------------------------------------------------------------
// Returns the millisecond tick equivalent for the date in the specified control.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// ctrl		element		The form element which will have its value validated.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME             DESCRIPTION
// 10/25/2000   George Pollard   Created

function getDateTicks(ctrl) {
	var regExpObj = new RegExp("^(\\d{1,2})/(\\d{1,2})/((\\d{2})|(\\d{4}))$")
	if (!regExpObj.test(ctrl.value)) 
		return 0;
	regExpObj.exec(ctrl.value);
	var month = RegExp.$1;
	var day = RegExp.$2;
	var year = RegExp.$3;
	var err = isValidDate(day,month,year);
	if (err!=null)
		return 0;
	if (day.length==1) day = "0"+day;
	if (month.length==1) month = "0"+month;
	if (year.length==2) year = "20"+year;
	//alert(day +" "+ month +" "+ year);
	return Date.UTC(year, month-1, day);
}

// -------------------------------------------------------------------------------
// Function         : validateDate(formElement, lowerBound, upperBound)
// -------------------------------------------------------------------------------
// This function validates dates entered into a form element and returns 
// an error if the value of the element is not in the correct range
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formElement	element		The form element which will have its value validated.
// lowerBound	number		The lower bound for the date range
// upperBound	number		The upper bound for the date range
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME             DESCRIPTION
// 10/25/2000   George Pollard   Created
// 11/22/2000   George Pollard   Updated

function validateDate(formElement, lowerBound, lowerInclusive, upperBound, upperInclusive) {
	if (formElement.value == '') {
		return true;
	}
	if (validateDateFormat(formElement, false)) {
		var minutes = getDateTicks(formElement) / 60000;	// drop 1/2 min because bounds are integers
		var aboveLowerBound = (lowerInclusive ? minutes >= lowerBound : minutes > lowerBound); 
		var belowUpperBound = (upperInclusive ? minutes <= upperBound : minutes < upperBound); 
		
		if (upperBound >= lowerBound) {
			if (aboveLowerBound && belowUpperBound)
				return true;
			else {
				var sLower = (lowerInclusive ?  CNINCLUSIVE :  CNEXCLUSIVE);
				var lowerDate = minutesToDate(lowerBound);
				var sUpper = (upperInclusive ?  CNINCLUSIVE :  CNEXCLUSIVE);
				var upperDate = minutesToDate(upperBound);
				handleCNError(CNVALIDERROR2 + '\n' + CNVALIDERROR3 + '\n' + CNVALIDERROR4   + lowerDate + sLower +   CNVALIDERROR6  + upperDate + sUpper);
			}
		} else {
			if (aboveLowerBound || belowUpperBound) 
				return true;
			else {
				var sLower = (lowerInclusive ?  CNEXCLUSIVE :  CNINCLUSIVE);
				var lowerDate = minutesToDate(lowerBound);
				var sUpper = (upperInclusive ?  CNEXCLUSIVE :  CNINCLUSIVE);
				var upperDate = minutesToDate(upperBound);
				handleCNError(CNVALIDERROR2 + '\n' + CNVALIDERROR3 + '\n' + CNVALIDERROR5   + upperDate + sUpper +   CNVALIDERROR6  + lowerDate + sLower);
			}
		}
	}

	// selects the field value
	formElement.focus();
	formElement.select();
	return false;
}

// -------------------------------------------------------------------------------
// Function         : submitCNForm(formObj)
// -------------------------------------------------------------------------------
// This function validates a form and submits it if it passes validation
// -------------------------------------------------------------------------------
// Returns true if the form has been submitted and false otherwise.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// formObj          formObj     The form to validate and submit
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function submitCNForm(formObj) {

	var returnValue = false;
	
	if(formObj) {
	
		// submits the form if it doesn't have an onsubmit event handler
		// or if the onsubmit event handler returns true
		if(!formObj.onsubmit || formObj.onsubmit()) {
			formObj.submit();
			returnValue = true;
		}
	}

	return returnValue;
	
}

// -------------------------------------------------------------------------------
// Function         : submitAndClose(formObj)
// -------------------------------------------------------------------------------
// This function submits a form and then closes the window
// -------------------------------------------------------------------------------
// Returns true if the form has been submitted and false otherwise.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME				TYPE        DESCRIPTION
// formObj          formObj     The form to validate and submit
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/06/2001   Chad Peck   Created

function submitAndClose(formObj) {
	
	var returnValue = false;
	
	if(formObj) {
		if(window.opener) {
			window.opener.name = "mainWindow";
			form.target = "mainWindow";
		}
		
		if(submitCNForm(formObj)) {
			self.close();
			returnValue = true;
		}
	}
	
	return returnValue;
	
}

// -------------------------------------------------------------------------------
// Function         : disableLinks()
// -------------------------------------------------------------------------------
// This function disables all links and forms on a page.
// -------------------------------------------------------------------------------
// Returns null
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME        DESCRIPTION
// 02/27/2001   Chad Peck   Moved from sitebuilderpublic.js

function disableLinks() {

	var linkIndex;
	var linksLength;
	var formIndex;
	var formsLength;
	
	linksLength = document.links.length;
	
	for(linkIndex=0; linkIndex < linksLength; linkIndex++) {
		var currentLink = document.links[linkIndex];
		currentLink.href = "javascript:void(0)";
		if(currentLink.onclick) {
			currentLink.onclick = "return false";
		}
	}
	
	formsLength = document.forms.length;
	
	for(formIndex=0; formIndex < formsLength; formIndex++) {
		var currentForm = document.forms[formIndex];
		currentForm.method = "get";
		currentForm.action = "javascript:void(0)";
		
		var elementLength = currentForm.elements.length;
		for(elementIndex=0; elementIndex < elementLength; elementIndex++) {
			var currentElement = currentForm.elements[elementIndex];
			if(currentElement.type != 'hidden') {
				currentElement.disabled = true;
			}
		}
	}
}

function XMLEncode(sIn) {

	sIn = sIn.replace(/&/g, "&amp;");
	sIn = sIn.replace(/</g, "&lt;");
	sIn = sIn.replace(/>/g, "&gt;");
	sIn = sIn.replace(/"/g, "&quot;");
	sIn = sIn.replace(/'/g, "&apos;");

	return sIn;

}

function MM_findObj(n, d) { //v3.0
  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&&document.getElementById) x = document.getElementById(n);
  return x;
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;

  for (i=0; i<(args.length-2); i+=3) {
    if ((obj=MM_findObj(args[i]))) {
      v=args[i+2];
      if (obj.style) {
        obj=obj.style;
        v=(v=='show')?'visible':(v='hide')?'hidden':v;
      }
      obj.visibility=v;
    }
  }
}

function showPane(formObj){

  var optionsLength = formObj.options.length;
  
  for(i=0; i < optionsLength; i++) {
    var currentOption = formObj.options[i];
    if(i == formObj.selectedIndex) {
      MM_showHideLayers(currentOption.value,'','show');
    } else {
      MM_showHideLayers(currentOption.value,'','hidden');
    }
  }
}

function replaceCRLF(str) {
  if(str && str.replace) {
	str = str.replace(/\r\n/g,"<br\/>");
	str = str.replace(/\n/g,"<br\/>");
  }
  return str;

}

// -------------------------------------------------------------------------------
// Function         : confirmPassword(formObj)
// -------------------------------------------------------------------------------
// Author           : Chad Peck
// Created on       : Friday, March 24, 2000
// 
// This function checks to make sure that two the values of a password field and
// a confirm password field match.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formObj		form		Reference to a form object.  It should always be
//							by the this keyword.
// -------------------------------------------------------------------------------
// Last Updated     : 
// Updated by       : 
// -------------------------------------------------------------------------------

function confirmPassword(formObj) {

	if (formObj.Password.value!=formObj.elements["_ConfirmPassword"].value) {
	
		formObj.Password.value="";
		formObj.elements["_ConfirmPassword"].value="";
		alert(CNREENTERPASSWORD + '\n' + CNNOTMATCH);
		return false;

	} else {

		return true;

	}

}


// -------------------------------------------------------------------------------
// Function         : confirmPassword2(formObj)
// -------------------------------------------------------------------------------
// Author           : Chad Peck
// Created on       : Friday, March 24, 2000
// 
// This function checks to make sure that two the values of a password field and
// a confirm password field match.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// formObj		form		Reference to a form object.  It should always be
//							by the this keyword.
// -------------------------------------------------------------------------------
// Last Updated     : 
// Updated by       : 
// -------------------------------------------------------------------------------

function confirmPassword2(formObj) {

	if (formObj.NewPassword.value!=formObj.elements["_ConfirmPassword"].value) {
	
		formObj.NewPassword.value="";
		formObj.elements["_ConfirmPassword"].value="";
		alert(CNREENTERPASSWORD + '\n' + CNNOTMATCH);
		return false;

	} else {

		return true;

	}

}

// -------------------------------------------------------------------------------
// Function         : checkCookiesOn(checkFlags)
// -------------------------------------------------------------------------------
// This function checks, on the client, whether cookies are enabled in the browser. 
// The function will check for Per-session cookies and/or for Stored cookies.
// A bit mask is returned indicating which types of cookies are enabled.  The  
// return value will be 0 if no cookie types are enabled; 1 if Per-session cookies 
// are enabled; 2 if Store cookies are enabled; 3 if both types are enabled.
// -------------------------------------------------------------------------------
// Parameters
// -------------------------------------------------------------------------------
// NAME			TYPE        DESCRIPTION
// checkFlags	number		A bit mask indicating which type of cookie(s) to check;
//							1 indicates check Per-session cookies; 2 indicates 
//							check Stored cookies; 3 or 0 indicates check both 
//							cookie types.
// -------------------------------------------------------------------------------
// History
// -------------------------------------------------------------------------------
// DATE			NAME             DESCRIPTION
// 06/19/2000   Barry Cline		 Created
//
var PERSESSION_COOKIE_FLAG = 1;
var STORED_COOKIE_FLAG = 2;
function checkCookiesOn(checkFlags)
{
	var index;
	var enabledFlags = 0;
		
	if (checkFlags == 0)
		//If we're not asked to check anything, then, obviously, we'll check everything.
		checkFlags = PERSESSION_COOKIE_FLAG + STORED_COOKIE_FLAG;
			
	if ((checkFlags & PERSESSION_COOKIE_FLAG) != 0)
	{	
		//Check whether Per-session cookie already exists
		index = document.cookie.indexOf(perSessionCookieName + "=");
		if (index == -1)
		{
			//Issue per-session check cookie
			var perSessionCookieName = "CNPerSessionCookieCheck";
			document.cookie = perSessionCookieName + "=True";
			//Try to retrieve per-session check cookie
			index = document.cookie.indexOf(perSessionCookieName + "=");
		}
		if (index != -1)
			enabledFlags += PERSESSION_COOKIE_FLAG;
	}	
	if ((checkFlags & STORED_COOKIE_FLAG) != 0)
	{
		//Check whether SITESERVER stored cookie already extant & available
		index = document.cookie.indexOf("SITESERVER=");
		if (index == -1)
		{
			//Issue stored check cookie
			var storedCookieName = "CNStoredCookieCheck";
			var today = new Date();
			var expiration = new Date(today.getTime() + 1 * 24 * 60 * 60 * 1000);
			document.cookie = storedCookieName + 
								"=True ; path=/; expires=" + expiration.toGMTString();
			//Try to retrieve stored check cookie
			index = document.cookie.indexOf(storedCookieName + "=");
			if (index != -1)
			{
				enabledFlags += STORED_COOKIE_FLAG;
				//Delete stored check cookie
				document.cookie = storedCookieName + 
									"=; path=/; expires=Tue, 01-Jan-80 00:00:01 GMT";
			}
		}
		else
		{
			enabledFlags += STORED_COOKIE_FLAG;
		}
	}
	return enabledFlags;
}


function checkAllCookies()
{	
	var checkFlags = PERSESSION_COOKIE_FLAG + STORED_COOKIE_FLAG;
	if ((checkCookiesOn(checkFlags) & checkFlags) == checkFlags)
		return 1;
	else
		return 0;
}

function checkStoredCookie()
{	
	var checkFlags = STORED_COOKIE_FLAG;
	if ((checkCookiesOn(checkFlags) & checkFlags) == checkFlags)
		return 1;
	else
		return 0;
}

function checkPerSessionCookie()
{	
	var checkFlags = PERSESSION_COOKIE_FLAG;
	if ((checkCookiesOn(checkFlags) & checkFlags) == checkFlags)
		return 1;
	else
		return 0;
}

// This code will be executed at the top of all 
// ChannelNet XSL template-derived Web pages
if (checkStoredCookie() == 0)
	document.location.href="/_mem_bin/nocookie.asp";

