var isNN = (navigator.appName.indexOf("Netscape")!=-1);


function CreateControl(DivID, CLSID, ObjectID, CodeBase, WIDTH, HEIGHT, URL, AUTOSTART)
{
  var d = document.getElementById(DivID);
  d.innerHTML = '<object classid="' + CLSID + '" id="' + ObjectID + '" codebase="' + CodeBase + '" width="' + WIDTH + '" height="' + HEIGHT +'"><param name="movie" value=' + URL + '><param name="quality" value="high"><embed src="' + URL + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + WIDTH + '" height="' + HEIGHT +'"></embed></object>';
}


function autoTab(input,len, e) {
	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();
	}
	return true;
}


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;
}


function numericOnly( obj, event ) { 
    var curChar    = String.fromCharCode( event.keyCode ); 
    var inpStr     = obj.value + curChar 

    result = inpStr.match( '^[0-9]+$' );
    if ( ! result ) {
        event.returnValue = false;
        event.cancel      = true; 
    }         
}

function RequestPin(){
	document.forms[0].action = 'requestpin.asp'
	document.forms[0].submit()
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}


function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


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_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



function updateError(strErrorMsg){
	if (!document.all&&!document.getElementById)
		return
	if (strErrorMsg.length > 0) {
	    thelement=document.getElementById? document.getElementById("spnErrorMsg"): document.all.spnErrorMsg
	    thelement.innerHTML=strErrorMsg
	}
}



function validatePhone () {
	var phone = parseInt (document.subscribe.phone.value);
			
	if ( isNaN(phone) ) {
		updateError ("Please fill out your mobile phone number before submitting.");
		document.subscribe.phone.focus();
		return false;
	}
	else if ( ( phone < 1000000000 ) || ( phone > 9999999999 ) ) {
		updateError ("Please Enter a Valid Phone Number.");
		document.subscribe.phone.focus();
		return false;
	}
	else {
		updateError ("");
	}	

	return true;
}

function validateZip () {
	var zip = document.subscribe.zip.value;
	var	i1, i2, i3, i4, i5;
		
	//	First make sure that the entered zip code has 5, and only 5, characters
	if ( zip.length != 5 ) {
		updateError ("The zip code you typed is not valid.  Please enter a valid 5-digit zip code.");
		document.subscribe.zip.focus();
		return false;
	}
	else {
		//	Now make sure that each of the 5 characters is a number
		i1 = parseInt (zip.charAt(0));
		i2 = parseInt (zip.charAt(1));
		i3 = parseInt (zip.charAt(2));
		i4 = parseInt (zip.charAt(3));
		i5 = parseInt (zip.charAt(4));
			
		if ( ( isNaN(i1) ) || ( isNaN(i2) ) || ( isNaN(i3) ) || ( isNaN(i4) ) || ( isNaN(i5) ) ) {
			updateError ("The zip code you typed is not valid.  Please enter a valid 5-digit zip code.");
			return false;
		}
	}
	updateError ("");
	return true;
}
	

		//ID Helper DHTML module toggle
		function toggleInstructions() {
			if(oBw.ie5||oBw.ns6){  //Disable function in unsupported browsers
			  	Istate = document.getElementById('instructions').style.display;
			  	if (Istate=='none') {
		    		Istate='block';
		  		}
		  		else {
		    		Istate='none';
		  		}
		  		document.getElementById('instructions').style.display=Istate;
			}
		}
		function toggleInstructionsOn() {
			if(oBw.ie5||oBw.ns6){  //Disable function in unsupported browsers
			  	Istate = document.getElementById('instructions').style.display;
		  		if (Istate=='none') {
		    			Istate='block';
		  		}
		  		else {
		    			Istate='block';
		  		}
			  	document.getElementById('instructions').style.display=Istate;
		  	}
		}
		//Toggle Alt Email Mandatory notation
		//switch layers for different browsers
		var ie4 = (document.all) ? true : false;
		var ns4 = (document.layers) ? true : false;
		var ns6 = (document.getElementById && !document.all) ? true : false;
		
		function hidelayer(lay) {
			if (ie4) {document.all[lay].style.visibility = "hidden";}
			if (ns4) {document.layers[lay].visibility = "hide";}
			if (ns6) {document.getElementById([lay]).style.display = "none";}
		}

		function showlayer(lay) {
			if (ie4) {document.all[lay].style.visibility = "visible";}
			if (ns4) {document.layers[lay].visibility = "show";}
			if (ns6) {document.getElementById([lay]).style.display = "block";}
		}


		function hideSelects(action) {
			//documentation for this script at http://www.shawnolson.net/a/1198/
			//possible values for action are 'hidden' and 'visible'
			if (action!='visible'){action='hidden';}
			if (navigator.appName.indexOf("MSIE")) {
				for (var S = 0; S < document.forms.length; S++){
					for (var R = 0; R < document.forms[S].length; R++) {
						if (document.forms[S].elements[R].options) {
							document.forms[S].elements[R].style.visibility = action;
						}
					}
				} 
			}
		}
		
		function yreg_pop(s){
			window.open(s,"yec_pop3","width=520,height=500,scrollbars=yes,resizable=yes");
		}



		
		function characterCount( obj, event ) {
			var thelement;
			var strString;
			
			if (!document.all&&!document.getElementById)
				return
			thelement=document.getElementById? document.getElementById("spnCharCount"): document.all.spnCharCount;
			
			if (getCharCount(obj.value) > 160) {
				strString = "<font color=red>" + getCharCount(obj.value) + " / 160</font>";
			} else {
				strString = getCharCount(obj.value) + " / 160</font>";
			}
			thelement.innerHTML=strString
		}
		
		function textCount( obj, event, idname ) {
					var thelement;
					var strString;
					
					if (!document.all&&!document.getElementById)
						return
					thelement=document.getElementById(idname);
					
					if (getCharCount(obj.value) > 160) {
						strString = "<font color=red>" + getCharCount(obj.value) + " / 160</font>";
					} else {
						strString = getCharCount(obj.value) + " / 160</font>";
					}
					thelement.innerHTML=strString
		}


		function getCharCount(strText) {
			//Update count for Tags
			//	[Location] = 50
				strText = strText.replace(/\[Location\]/gi, "12345678901234567890");
			//	[Phone] = 14
				strText = strText.replace(/\[Phone\]/gi, "12345678901234");
			//	[StoreCode] = 5
				strText = strText.replace(/\[StoreCode\]/gi, "12345");
			//	[TextCode] = 5
				strText = strText.replace(/\[TextCode\]/gi, "12345");
			//	[Address] = 50
				strText = strText.replace(/\[Address\]/gi, "12345678901234567890123456789012345678901234567890");
			//	[City] = 30
				strText = strText.replace(/\[City\]/gi, "123456789012345678901234567890");
			//	[ST] = 2
				strText = strText.replace(/\[ST\]/gi, "12");
			//	[ZIP] = 5
				strText = strText.replace(/\[Zip\]/gi, "12345");
			//	[Exp:M/D/YY] = 12
				strText = strText.replace(/\[Exp:M\/D\/YY\]/gi, "123456789012");
			//	[----- BeginNew -----] = 2
				strText = strText.replace(/\[----- BeginNew -----\]/gi, "12");
			//	[MsgX/Y] = 6
				strText = strText.replace(/\[MsgX\/Y\]/gi, "123456");
				strText = strText.replace(/\[Msg1\/3\]/gi, "123456");
				strText = strText.replace(/\[Msg2\/3\]/gi, "123456");
				strText = strText.replace(/\[Msg3\/3\]/gi, "123456");
				strText = strText.replace(/\[Msg1\/2\]/gi, "123456");
				strText = strText.replace(/\[Msg2\/2\]/gi, "123456");
								
			//	[GiftValue1] = 5
				strText = strText.replace(/\[GiftValue1\]/gi, "12345");
			//	[GiftValue2] = 5
				strText = strText.replace(/\[GiftValue2\]/gi, "12345");
			//	[GiftValue3] = 5
				strText = strText.replace(/\[GiftValue3\]/gi, "12345");
				
			//Update count for special characters remaining.
			//	<Euro Symbol removed>
				//strText = strText.replace(/<Euro Symbol removed>/, "12");
			//	[ or ]
				strText = strText.replace(/\[/gi, "12");
				strText = strText.replace(/\]/gi, "12");
			//	\
				strText = strText.replace(/\\/gi, "12");
			//	^
				strText = strText.replace(/\^/gi, "12");
			//	{ or }
				strText = strText.replace(/\{/gi, "12");
				strText = strText.replace(/\}/gi, "12");
			//	|
				strText = strText.replace(/\|/gi, "12");
			//	~
				strText = strText.replace(/~/gi, "12");
			//	CRLF - Handled automatically
			
			return eval(strText.length);
		}
		
		function checkCharCount(obj, event) {
			if (getCharCount(obj.value) < 160) {
				event.returnValue	= true;
				event.cancel		= false;
			} else {
				event.returnValue	= false;
				event.cancel		= true;
			}
		}


		function trim(inputString) {
		   // Removes leading and trailing spaces from the passed string. Also removes
		   // consecutive spaces and replaces it with one space. If something besides
		   // a string is passed in (null, custom object, etc.) then return the input.
		   if (typeof inputString != "string") { return inputString; }
		   var retValue = inputString;
		   var ch = retValue.substring(0, 1);
		   while (ch == " ") { // Check for spaces at the beginning of the string
		      retValue = retValue.substring(1, retValue.length);
		      ch = retValue.substring(0, 1);
		   }
		   ch = retValue.substring(retValue.length-1, retValue.length);
		   while (ch == " ") { // Check for spaces at the end of the string
		      retValue = retValue.substring(0, retValue.length-1);
		      ch = retValue.substring(retValue.length-1, retValue.length);
		   }
		   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
		      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
		   }
		   return retValue; // Return the trimmed string back to the user   
		}
		
		
		function validateDecimal(sender) {
                if (sender.value.match(/(\d+)?\.*\d*/))
                    return true;
                else
                    return false;
        }
		
		function checkForSecondDecimal(sender, e) {
		    formatBox = document.getElementById(sender.id);
		    strLen = sender.value.length;
		    strVal = sender.value;
		    hasDec = false;
		    e = (e) ? e : (window.event) ? event : null;
   
		    if (e) {
		        var charCode = (e.charCode) ? e.charCode :
		                    ((e.keyCode) ? e.keyCode :
		                    ((e.which) ? e.which : 0));
   
		        if ((charCode == 46) || (charCode == 110) || (charCode == 190)) {
		            for (var i = 0; i < strLen; i++) {
		                hasDec = (strVal.charAt(i) == '.');
		                if (hasDec)
		                    return false;
		            }
		        }
		    }
		    return true;
		}

		function DisplayLocInfo(storename, abbvname, storenum, storecode, address, address2, city, state, zip, phone, contact) {
			document.write('<SPAN ');
			LocationInfo(storename,storecode,address,address2,city,state,zip,phone,contact);
			document.write('>' + unescape(abbvname) + " (" + unescape(storenum) + ")" + '</SPAN>');
		}
		
		function LocationInfo(locname,storecode,address,address2,city,st,zip,phone,contact) {
				var ToolTipText;
              
				if (locname != '')   { ToolTipText = locname }; 
				if (storecode != '') { ToolTipText = ToolTipText + '<br>Text Code: ' + storecode };
				if (address != '')   { ToolTipText = ToolTipText + '<br>' + address };
				if (address2 != '')  { ToolTipText = ToolTipText + '<br>' + address2 };
				if (city != '')      { ToolTipText = ToolTipText + '<br>' + city + ', ' + st + ' ' + zip };
				if (contact != '')   { ToolTipText = ToolTipText + '<br>' + contact };
				if (phone != '')     { ToolTipText = ToolTipText + '<br>' + phone };
				
				DisplayBalloonTip(ToolTipText);
        }
        
        function DisplayBalloonTip(ToolTip) {
			document.write('onmouseover="Tip(\'' + ToolTip ); 
			document.write('\', BALLOON, true, CENTERMOUSE, true, ABOVE, true, OFFSETX, 0, DELAY, 0\);" onmouseout="UnTip\(\);"');
		}
        
        function addslashes( str ) {
		    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
		}

		function hideElement (elementId) {
			var element;
			if (document.all)
				element = document.all[elementId];
			else if (document.getElementById)
				element = document.getElementById(elementId);
			if (element && element.style)
					element.style.display = 'none';
		}

		function showElement (elementId) {
			var element;
			if (document.all)
				element = document.all[elementId];
			else if (document.getElementById)
				element = document.getElementById(elementId);
			if (element && element.style)
				element.style.display = '';
		}

		
		function setSelRange(inputEl, selStart, selEnd) {  
			if (inputEl.setSelectionRange) {   
				inputEl.focus();   
				inputEl.setSelectionRange(selStart, selEnd);  
			} 
			else if (inputEl.createTextRange) {   
				var range = inputEl.createTextRange();   
				range.collapse(true);   
				range.moveEnd('character', selEnd);   
				range.moveStart('character', selStart);   
				range.select();  
			} 
		}
		
		function cursorPosition(strElementName){
			var textarea = document.getElementById(strElementName);
			textarea.focus();
			
			// get selection in firefox, opera, ...
			if (typeof(textarea.selectionStart) == 'number')
		 
			{	return textarea.selectionStart;
				
			}else if(document.selection){
				var selection_range = document.selection.createRange().duplicate();
		 
				if (selection_range.parentElement() == textarea) {    // Check that the selection is actually in our textarea
				// Create three ranges, one containing all the text before the selection,
				// one containing all the text in the selection (this already exists), and one containing all
				// the text after the selection.
				var before_range = document.body.createTextRange();
				before_range.moveToElementText(textarea);                    // Selects all the text
				before_range.setEndPoint("EndToStart", selection_range);     // Moves the end where we need it
		 
				var after_range = document.body.createTextRange();
				after_range.moveToElementText(textarea);                     // Selects all the text
				after_range.setEndPoint("StartToEnd", selection_range);      // Moves the start where we need it
		 
				var before_finished = false, selection_finished = false, after_finished = false;
				var before_text, untrimmed_before_text, selection_text, untrimmed_selection_text, after_text, untrimmed_after_text;
		 
				// Load the text values we need to compare
				before_text = untrimmed_before_text = before_range.text;
				selection_text = untrimmed_selection_text = selection_range.text;
				after_text = untrimmed_after_text = after_range.text;
		 
				// Check each range for trimmed newlines by shrinking the range by 1 character and seeing
				// if the text property has changed.  If it has not changed then we know that IE has trimmed
				// a \r\n from the end.
				do {
				  if (!before_finished) {
				      if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
				          before_finished = true;
				      } else {
				          before_range.moveEnd("character", -1)
				          if (before_range.text == before_text) {
				              untrimmed_before_text += "\r\n";
				          } else {
				              before_finished = true;
				          }
				      }
				  }
				  if (!selection_finished) {
				      if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
				          selection_finished = true;
				      } else {
				          selection_range.moveEnd("character", -1)
				          if (selection_range.text == selection_text) {
				              untrimmed_selection_text += "\r\n";
				          } else {
				              selection_finished = true;
				          }
				      }
				  }
				  if (!after_finished) {
				      if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
				          after_finished = true;
				      } else {
				          after_range.moveEnd("character", -1)
				          if (after_range.text == after_text) {
				              untrimmed_after_text += "\r\n";
				          } else {
				              after_finished = true;
				          }
				      }
				  }
		 
				} while ((!before_finished || !selection_finished || !after_finished));
		 
				// Untrimmed success test to make sure our results match what is actually in the textarea
				// This can be removed once you're confident it's working correctly
				//var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
				//var untrimmed_successful = false;
				//if (textarea.value == untrimmed_text) {
				//  untrimmed_successful = true;
				//}
				// ** END Untrimmed success test
		 
				var startPoint = untrimmed_before_text.length;
				//alert(startPoint);
				return startPoint;
				}
			}
		}

		function getMacro(strTextArea) {
			var i = 0;
			var j = 0;
			var curPos = cursorPosition(strTextArea);
			var textarea = document.getElementById(strTextArea);
			var strText = textarea.value;
			
			var intTotLen = strText.length
			var intStart = -1;
			var intEnd = -1;
			var intLineBreakCount = 0;
			
			//Count all line breaks up to the cursor position
			j = curPos;
			for (i = 0;  i <= curPos;  i++)
			{
				if (strText.substr(i,1)=="\r") {j = j-1}
			}
			curPos = j;
			strText = strText.replace(/\r/g,'');
			
			if (curPos > intTotLen) { curPos = intTotLen }
						
			//Get Starting Bracket [
			for (i = curPos-1; i >= 0;  i--)
            {
				//if (strText.substr(i,1)=="\n") { i-- }
				if (strText.substr(i,1)==']' || strText.substr(i,1)=="\n") { intStart=-1; break; }
				if (strText.substr(i,1)=='[') {	intStart=i; break; }
			}
            
            //Get Ending Bracket ]
            for (i = curPos; i <= intTotLen;  i++)
            {
				//if (strText.substr(i,1)=="\n") { i++ }
				if (strText.substr(i,1)=='[' || strText.substr(i,1)=="\n") { intEnd=-1; break; }
				if (strText.substr(i,1)==']') { intEnd=i+1; break; }
            }
            
            //alert(intStart + ', ' + intEnd);
            
            if (intStart >= 0 && intEnd > 0) {
				setSelRange(textarea, intStart, intEnd);
			}
		}
		
		function clearBrokenMacro(strTextArea) {
			var i = 0;
			var j = 0;
			var curPos = cursorPosition(strTextArea);
			var textarea = document.getElementById(strTextArea);
			var strText = textarea.value;
			var blnFoundOpenBracket = false;
			var blnFoundClosedBracket = false;
			
			var intTotLen = strText.length
			var intStart = -1;
			var intEnd = -1;
			var intLineBreakCount = 0;
			
			//Count all line breaks up to the cursor position
			j = curPos;
			for (i = 0;  i <= curPos;  i++)
			{
				if (strText.substr(i,1)=="\r") {j = j-1}
			}
			curPos = j;
			strText = strText.replace(/\r/g,'');
			
			if (curPos > intTotLen) { curPos = intTotLen }
						
			//Get Starting Bracket [
			for (i = curPos-1; i >= 0;  i--)
            {
				if (strText.substr(i,1)==' ' || strText.substr(i,1)=='\n' || strText.substr(i,1)==']') { intStart=i+1; break; }
				if (strText.substr(i,1)=='[') {	intStart=i; blnFoundOpenBracket=true; break; }
			}
            
            //Get Ending Bracket ]
            for (i = curPos; i <= intTotLen;  i++)
            {
				//alert(strText.substr(i,1));
				//if (strText.substr(i,1)=="\n") { i++ }
				if (strText.substr(i,1)==' ' || strText.substr(i,1)=='\n' || strText.substr(i,1)=='[') { intEnd=i; break; }
				if (strText.substr(i,1)==']') { intEnd=i+1; blnFoundClosedBracket=true; break; }
            }
            
            if ((blnFoundOpenBracket && !blnFoundClosedBracket) || (!blnFoundOpenBracket && blnFoundClosedBracket)) {
				document.getElementById(strTextArea).value = strText.substr(0,intStart) + strText.substr(intEnd,intTotLen);
				setSelRange(textarea, intStart, intStart);
			}
		}
		
		function wordcount(count) {
			var words = count.split(/\s/);
			cnt = words.length;
			wordcount = cnt;
		}

		function setMacro(myField, myValue) {
			// IE support
			if (document.selection) {
				myField.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
			}
			// Netscape
			else if (myField.selectionStart || myField.selectionStart == '0') {
				var startPos = myField.selectionStart;
				var endPos = myField.selectionEnd;
				myField.value = myField.value.substring(0, startPos)
				              + myValue
				              + myField.value.substring(endPos, myField.value.length);
			} else {
				myField.value += myValue;
			}
		} 
		
		function getLastMacroPos(strText) {
			var i;
			var blnfound = false;
			var intStart = strText.length;
			var intEnd = 0;
			
			for (i = 0;  i < strText.length;  i++)
            {
				if (strText.substr(i,1)=='[') { intStart = i }
				if (strText.substr(i,1)==']' && intStart < strText.length) { 
					intEnd = i+1; 
					intStart = strText.length; //reset start tag
				}
            }
            return intEnd
        }
        
        function updateExpDateTag(strAction,strElement) {
			var cpnText = document.getElementById(strElement).value;
			var blnResult = false;
			
			if (strAction == 'add' ) {
				if (cpnText.substr(cpnText.length-12,cpnText.length)!='[Exp:M/D/YY]') {document.getElementById(strElement).value = cpnText + '[Exp:M/D/YY]'; blnResult = true}
			}
			
			if (strAction == 'remove') {
				if (cpnText.substr(cpnText.length-12,cpnText.length)=='[Exp:M/D/YY]') {document.getElementById(strElement).value = cpnText.substr(0,cpnText.length-12); blnResult = true}
			}
			return blnResult
		}
		
		
