// This file contains the JavaScript for the Valley Community Bank web site.

vcb = {

	fixBrowserInconsistenciesPrePage: function() {
		// if we have any browser issues, deal with them here. This is called while
		// the header is loading AFTER the css file, so it can be used to override CSS
		// with document.write.
	},
	
	init: function() {
		// this is the window load event handler. Called once after all the HTML is loaded.
		if (!document.getElementById) return;
		
		vcb.safari = true ? (navigator.userAgent.toLowerCase().indexOf('safari') != -1) : false;

		// login form validation setup
		vcb.loginFormSetup();

		if (!document.getElementsByTagName) return;
		
		// on the home page, set up the S3 popup
		vcb.homePopup();

		// gray/white alternate rate chart tables
		vcb.rateChartTables();
		
		// add focus event for banner link to home page and menus
		vcb.noBlur('banner');
		vcb.noBlur('hmenu');
		vcb.noBlur('lmenu');
		
		// modify top of page links to scroll without changing the location
		vcb.pageTops();
		
	},
	
	homePopup: function() {
		if (document.getElementsByTagName('body')[0].className.search(/\bhome\b/)) return;
		var theLink = document.getElementById('s3logo');
		if (!theLink) return;
		
		// first create a div for the image, and place the image on it
		var thePopDiv = document.createElement('div');
		vcb.popDiv = thePopDiv;
		thePopDiv.style.display = 'none';
		thePopDiv.style.position = 'absolute';
		thePopDiv.style.width = '388px';
		thePopDiv.style.height = '553px';
		vcb.setDivLocation();
		thePopDiv.style.zIndex = 100;
		// the image is a 24-bit PNG with transparency, deal with Microsoft lack of real support
		if (document.body.filters) {
			thePopDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/popup.png')";
		} else {
			var img = document.createElement('img');
			img.src = 'images/popup.png';
			thePopDiv.appendChild(img);
		}
		
		// now create the two text blocks (green text)
		var t1 = document.createElement('div');
		t1.style.display = 'block';
		t1.style.position = 'absolute';
		t1.style.left = '45px';
		t1.style.top = '210px';
		t1.style.width = '284px';
		t1.style.height = '95px';
		t1.style.fontWeight = 'bold';
		t1.innerHTML = '<p>At Valley Community Bank we believe that each of our customers deserves the very best in banking services. We deliver a great banking experience by focusing on 3 fundamental guildelines:</p>';

		var t2 = document.createElement('div');
		t2.style.display = 'block';
		t2.style.position = 'absolute';
		t2.style.left = '45px';
		t2.style.top = '414px';
		t2.style.width = '284px';
		t2.style.height = '95px';
		t2.style.fontSize = '140%';
		t2.style.lineHeight = '140%';
		t2.style.fontWeight = 'bolder';
		t2.innerHTML = '<p>We call it our S3 method.</p><p><i>You might say it&rsquo;s become second<br />nature for us!</i></p>';

		// append the text blocks to the popup div, and then append the popup div to "wholepage"
		thePopDiv.appendChild(t1);
		thePopDiv.appendChild(t2);
		
		// setup fader variables for the div (only used for non-MSIE browsers)
		thePopDiv.opState = 'dim';
		thePopDiv.opInt = null;
		thePopDiv.minOp = 0;
		thePopDiv.opStep = 10;
		thePopDiv.opVis = thePopDiv.minOp;
		thePopDiv.opTog = 'out';
		if (! document.body.filters)
			vcb.setOpacity(thePopDiv);

		var wp = document.getElementById('wholepage');
		wp.appendChild(thePopDiv);
		
		// setup click events
		vcb.addEvent(theLink, 'click', vcb.togglePopup, false);
		vcb.addEvent(thePopDiv, 'click', vcb.togglePopup, false);
		vcb.addEvent(thePopDiv, 'mousedown', vcb.popDivMouseDown, false);
		vcb.addEvent(thePopDiv, 'mouseup', vcb.popDivMouseUp, false);
		vcb.addEvent(thePopDiv, 'mouseout', vcb.popDivMouseUp, false);
		vcb.addEvent(thePopDiv, 'mousemove', vcb.popMouseMove, false);
		if (vcb.safari) {
			thePopDiv.onmousedown = thePopDiv.onmousemove = thePopDiv.onmouseup = thePopDiv.onmouseout = function() { return false;};
		}
		
		// fade effect for S3 logo
		theLink.opState = 'dim';
		theLink.opInt = null;
		theLink.minOp = 90;
		theLink.opStep = 1;
		theLink.opVis = theLink.minOp;
		vcb.setOpacity(theLink);
		vcb.addEvent(theLink, 'mouseover', vcb.mouseOn, false);
		vcb.addEvent(theLink, 'mouseout', vcb.mouseOut, false);
	},
	
	setDivLocation: function() {
		// initialize the popup div location in it's "proper" place
		vcb.popDiv.topLoc = 150;
		vcb.popDiv.leftLoc = 200;
		vcb.popDiv.style.top = '150px';
		vcb.popDiv.style.left = '200px';
		vcb.popDiv.mouseDown = false;
		vcb.popDiv.haveMoved = false;
	},
	
	popDivMouseDown: function(e) {
		var theDiv = vcb.getTarget(e, 'div');
		if (!theDiv) return;
		theDiv.style.cursor = 'pointer';
		var theEvent = window.event ? window.event : e;
		//alert ('start: ' + theEvent.screenX + ', ' + theEvent.screenY);
		theDiv.startX = theEvent.screenX;
		theDiv.startY = theEvent.screenY;
		theDiv.mouseDown = true;
		vcb.knackerEvent(e);
	},
	
	popDivMouseUp: function(e) {
		var theDiv = vcb.getTarget(e, 'div');
		if (!theDiv) return;
		theDiv.style.cursor = '';
		if (!theDiv.mouseDown) {
			vcb.knackerEvent(e);
			return;
		}
		var left = parseInt(theDiv.style.left);
		var top = parseInt(theDiv.style.top);
		theDiv.leftLoc = left;
		theDiv.topLoc = top;
		theDiv.mouseDown = false;
		vcb.knackerEvent(e);
	},
	
	popMouseMove: function(e) {
		//alert('mousemove');
		var theDiv = vcb.getTarget(e, 'div');
		if (!theDiv) return;
		if (!theDiv.mouseDown) return;
		var theEvent = window.event ? window.event : e;
		if (theEvent.button == 0) {
			theDiv.mouseDown = false;
			return;
		}
		var difX = theDiv.startX - theEvent.screenX;
		var difY = theDiv.startY - theEvent.screenY;
		var newLeft = theDiv.leftLoc - difX;
		var newTop = theDiv.topLoc - difY;
		theDiv.style.top = newTop + 'px';
		theDiv.style.left = newLeft + 'px';
		theDiv.haveMoved = true;
		vcb.knackerEvent(e);
	},
	
	togglePopup: function(e) {
		// toggle the display style of the popup div between block and none
		// for MSIE, and between fadein and fadeout for others
		if (vcb.popDiv.haveMoved) {
			vcb.popDiv.haveMoved = false;
			vcb.knackerEvent(e);
			return;
		}
		if (document.body.filters) {
			if (vcb.popDiv.style.display == 'block')
				vcb.popDiv.style.display = 'none';
			else {
				vcb.setDivLocation();
				vcb.popDiv.style.display = 'block';
			}
		} else {
			if (vcb.popDiv.opTog == 'out') {
				vcb.setDivLocation();
				vcb.popDiv.opTog = 'in';
				if (vcb.popDiv.opState != 'full') {
					vcb.popDiv.opState = 'fadein';
					if (vcb.popDiv.opInt == null)
						vcb.popDiv.opInt = setInterval(function() {vcb.fader(vcb.popDiv);}, 50);
				}
			} else {
				vcb.popDiv.opTog = 'out';
				if (vcb.popDiv.opState != 'dim') {
					vcb.popDiv.opState = 'fadeout';
					if (vcb.popDiv.opInt == null)
						vcb.popDiv.opInt = setInterval(function() {vcb.fader(vcb.popDiv);}, 50);
				}
			}
		}
	},
	
	mouseOut: function(e) {
		var theImg = vcb.getTarget(e, 'img');
		if (!theImg) return;
		theImg.style.cursor = '';
		if (theImg.opState != 'dim') {
			theImg.opState = 'fadeout';
			if (theImg.opInt == null)
				theImg.opInt = setInterval(function() {vcb.fader(theImg);}, 50);
		}
		vcb.knackerEvent(e);
	},
	
	mouseOn: function(e) {
		var theImg = vcb.getTarget(e, 'img');
		if (!theImg) return;
		theImg.style.cursor = 'pointer';
		if (theImg.opState != 'full') {
			theImg.opState = 'fadein';
			if (theImg.opInt == null)
				theImg.opInt = setInterval(function() {vcb.fader(theImg);}, 50);
		}
		vcb.knackerEvent(e);
	},
			
	fader: function(theImg) {
		if (theImg.opState == 'fadein') {
			if (theImg.opVis <= 0)
				theImg.style.display = 'block';
			theImg.opVis += theImg.opStep;
			vcb.setOpacity(theImg);
			if (theImg.opVis >= 100) {
				theImg.opState = 'full';
				clearInterval(theImg.opInt);
				theImg.opInt = null;
			}
		} else if (theImg.opState == 'fadeout') {
			theImg.opVis -= theImg.opStep;
			vcb.setOpacity(theImg);
			if (theImg.opVis <= theImg.minOp) {
				theImg.opState = 'dim';
				clearInterval(theImg.opInt);
				theImg.opInt = null;
				if (theImg.minOp == 0)
					theImg.style.display = 'none';
			}
		}
	},
	
	setOpacity: function(theImg) {
		var op = theImg.opVis;
		var opFrac = (op >= 100) ? 0.999 : op / 100; // Safari won't work if we let opFrac go to 1.0
		if (typeof theImg.filters == "object") {
			if (navigator.platform == 'Win32') {
				//alert('win32 opacity');
				theImg.filters.alpha.opacity = op;
			}
		} else {
			if (typeof theImg.style.opacity != "undefined") {
				theImg.style.opacity = opFrac;
			} else if (typeof theImg.style.MozOpacity != "undefined") {
				theImg.style.MozOpacity = opFrac;
			}
		}
	},

	pageTops: function() {
		// find all anchors with classname 'ptop' and install a handler that
		// scrolls the window to 0,0 and stops default action.
		if (!window.scroll) return;

		var ptlinks = vcb.getElementsByClassName(document, 'a', 'ptop');
		var ptop;
		while (ptop = ptlinks.shift()) {
			vcb.addEvent(ptop, 'click', vcb.topClickEvent, false);
			if (vcb.safari) {
				ptop.onclick = vcb.topOnClickEvent;
			}
		}
	},
	
	topClickEvent: function(e) {
		if (location.hash && location.hash.length > 0) return;
		window.scroll(0,0);
		vcb.knackerEvent(e);
	},

	topOnClickEvent: function() {	// for safari
		if (location.hash && location.hash.length > 0) return true;
		return false;
	},
	
	loginFormSetup: function() {
		// if this page has a form with id="currentUserLogon" hook it
		// up with validation code.
		var theForm = document.getElementById('currentUserLogon');
		if (! theForm) return;	// no currentUserLogin form on this page
		
		// assign an Object for each validation. Each gets:
		// - an element reference
		// - a type (reg for regular expression match, ne for not equal to another element, minlen for minimum length)
		// - for type reg, a regular expression.
		// - for type ne, another element reference
		// = for minlen, a count
		// - an error message
		// - an indication to clear the element if the test fails
		
		// 'trim' isn't an actual test. It instructs the validator to trim edge whitespace
		var trimAccId = new Object();
		trimAccId.elm = document.getElementById('AccessId');
		trimAccId.type = 'trim';
		
		var trimPw = new Object();
		trimPw.elm = document.getElementById('Password');
		trimPw.type = 'trim';

		// Using separate validation tests for "too short" gives more descriptive
		// error messages than using something like /^\w{8,}$/ in the regexp test.
		var accIdLen = new Object();
		accIdLen.elm = document.getElementById('AccessId');
		accIdLen.type = 'minlen';
		accIdLen.len = 8;
		accIdLen.errMsg = 'Access ID is too short';
		accIdLen.clearIt = false;

		var accIdReg = new Object();
		accIdReg.elm = document.getElementById('AccessId');
		accIdReg.type = 'reg';
		accIdReg.reg = /^\w+$/;
		accIdReg.errMsg = 'Access ID is not valid';
		accIdReg.clearIt = false;
		
		var pwdLen = new Object();
		pwdLen.elm = document.getElementById('Password');
		pwdLen.type = 'minlen';
		pwdLen.len = 6;
		pwdLen.errMsg = 'Password is too short';
		pwdLen.clearIt = true;

		var pwdReg = new Object();
		pwdReg.elm = document.getElementById('Password');
		pwdReg.type = 'reg';
		pwdReg.reg = /^\w+$/;
		pwdReg.errMsg = 'Password is not valid';
		pwdReg.clearIt = true;
		
		var pwdEq = new Object();
		pwdEq.elm = document.getElementById('Password');
		pwdEq.type = 'ne';
		pwdEq.elm2 = document.getElementById('AccessId');
		pwdEq.errMsg = 'Password cannot be the same as Access ID';
		pwdEq.clearIt = true;

		// the event handler will run the tests in this order
		theForm.valItems = Array(trimAccId, trimPw, accIdLen, accIdReg, pwdLen, pwdReg, pwdEq);
		
		// reference the form's error message span (one for all error messages)
		theForm.errorMsgSpan = document.getElementById('currentUserLogonErrs');
		theForm.allFieldsValid = true;
		
		// setup the event handler and the "on" handler for form submit event
		vcb.addEvent(theForm, 'submit', vcb.formSubmitEvent, false);
		if (vcb.safari) {
			theForm.onsubmit = vcb.formOnSubmit;
		}
		
	},
	
	formSubmitEvent: function(e) {
		// generic form submit event handler. Validate input against
		// form.valItems (as set up in the form-specific setup function.)
		var targ = vcb.getTarget(e, 'form');
		if (!targ) return;
		
		if (targ.errorMsgSpan)
			targ.errorMsgSpan.innerHTML = '';	// clear error message span

		if (!targ.valItems) return;

		var valItems = targ.valItems;
		var allValid = true;
		var errMsg = null;
		for (var i=0; i < valItems.length; i++) {
			// validation item loop
			var theItem = valItems[i];
			var result = true;
			// do the test
			if (theItem.type == 'trim')  { // not a test, just trim edge whitespace
				// Macintosh MSIE won't load this script if we use the inline syntax.
				// This way, the that browser still doesn't work, but at least the rest of
				// the script file does.
				var rege = new RegExp("^\\s*(.*?)\\s*$", '');
				theItem.elm.value = theItem.elm.value.replace(rege, "$1");
				//theItem.elm.value = theItem.elm.value.replace(/^\s*(.*?)\s*$/, "$1");
				//alert('trim: [' + theItem.elm.value + ']');
			} else if (theItem.type == 'reg')
				result = theItem.reg.test(theItem.elm.value);
			else if (theItem.type == 'ne') // bypass this test if item has zero length
				result = (theItem.elm.value.length == 0) || (theItem.elm.value != theItem.elm2.value);
			else if (theItem.type == 'minlen') // allow zero length for this test
				result = (theItem.elm.value.length == 0) || (theItem.elm.value.length >= theItem.len);
			// check the result
			if (! result) {
				// validation failed.
				if (targ.errorMsgSpan) {
					if (allValid)
						errMsg = '<span class="formerr">Please correct:</span><br />';
					else
						errMsg += '<br />';
					errMsg += theItem.errMsg;
				}
				if (theItem.clearIt)
					theItem.elm.value = '';
				allValid = false;
			}
		}

		if (errMsg)
			targ.errorMsgSpan.innerHTML = errMsg; // display error message(s)

		targ.allFieldsValid = allValid;
		
		if (!allValid)
			vcb.knackerEvent(e);		// stop default action
		else
			vcb.stopPropagation(e);		// just halt bubbling
	},
	
	formOnSubmit: function() {
		// generic onsubmit handler for browsers that don't obey preventDefault (Safari)
		return this.allFieldsValid;
	},
	
	rateChartTables: function() {
		// gray/white alternate table row backgrounds (rate charts)
		var tabls = document.getElementsByTagName('table');
		for (var t=0; t<tabls.length; t++) {
			var theTable = tabls[t];
			if (theTable.className.toLowerCase().search(/\brchart\b/) != -1) {
				// it's a rate chart
				var trs = theTable.getElementsByTagName('tr');
				var rcnt = 0;
				for (var r=0; r<trs.length; r++) {
					var theTr = trs[r];
					if (theTr.className.toLowerCase().search(/\bsep\b/) != -1)
						rcnt = 0;	// reset rcnt when we encounter a "sep" row.
					else if (theTr.className.toLowerCase().search(/\balt\b/) != -1) {
						// it's an "alt" row - change background style for all td's within.
						rcnt += 1;
						var tds = theTr.getElementsByTagName('td');
						for (var i=0; i < tds.length; i++) {
							var theTd = tds[i];
							if (rcnt % 2 == 0) {
								// light gray background here
								theTd.style.backgroundColor = '#e8e8e8';
							} else {
								theTd.style.backgroundColor = 'white';
							}
						}
					}
				}
			}
		}
		// end gray out alternate table row backgrounds (rate charts)
	},

	noBlur: function(id) {
		// set an event handler that blurs the anchor on focus
		// argument is the id of a container. Process all the links within it.
		var theObj = document.getElementById(id);
		if (theObj) {
			var anchrs = theObj.getElementsByTagName('a');
			for (var i=0; i < anchrs.length; i++)
				vcb.addEvent(anchrs[i], 'focus', vcb.blurMe, false);
		}
	},
	
	blurMe: function(e) {	// handle onfocus logo and menu links
		var targ = vcb.getTarget(e, 'a');
		if (targ) targ.blur();
		vcb.knackerEvent(e);
	},
	
	addEvent: function(element, eventType, lamdaFunction, useCapture, altFunc) {
		if (element.addEventListener) {
			element.addEventListener(eventType, lamdaFunction, useCapture);
			return true;
		} else if (element.attachEvent) {
			var r = element.attachEvent('on' + eventType, lamdaFunction);
			return r;
		} else {
			element['on' + eventType] = altFunc ? altFunc : lamdaFunction;
			return true;
		}
	},

	getTarget: function(e, tname)
	{
		// called to get the target of an event handler. Follow the DOM tree
		// up until we find a tag that matches tname. Return null on failure.
		var target = window.event ? window.event.srcElement : e ? e.target : null;
		
		if (!target) return null;

		if (!tname) {
			if (target.nodeType == 3) return target.parentNode;
			else return target;
		}
		var ltname = tname.toLowerCase();
		while (target != document.body && target.nodeName.toLowerCase() != ltname) {
			target = target.parentNode;
		}
		if (target.nodeName.toLowerCase() == ltname)
			return target;
		else
			return null;
	},

    stopPropagation: function(eventObject)
	{
		if (vcb.safari) return;

		if (eventObject && eventObject.stopPropagation) {
			eventObject.stopPropagation();
		}
		if (window.event) {
			window.event.cancelBubble = true;
		}
	},
	
	knackerEvent: function(eventObject) {
		if (vcb.safari) return;

		vcb.stopPropagation(eventObject);
		
		if (eventObject && eventObject.preventDefault) {
			eventObject.preventDefault();
		}
		if (window.event) {
			window.event.returnValue = false;
		}
	},
	
	getElementsByClassName: function (oElm, strTagName, oClassNames) {
		// http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
		// ex: getElementsByClassName(document, "a", "info-links");
		// ex: getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]); 
		var arrElements = (strTagName == "*" && document.all)? document.all : 
		oElm.getElementsByTagName(strTagName);
		var arrReturnElements = new Array();
		var arrRegExpClassNames = new Array();
		if(typeof oClassNames == "object"){
			for(var i=0; i<oClassNames.length; i++){
				arrRegExpClassNames.push(new RegExp("(^|\\s)" + 
				oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
			}
		}
		else{
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + 
			oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
		}
		var oElement;
		var bMatchesAll;
		for(var j=0; j<arrElements.length; j++){
			oElement = arrElements[j];
			bMatchesAll = true;
			for(var k=0; k<arrRegExpClassNames.length; k++){
				if(!arrRegExpClassNames[k].test(oElement.className)){
					bMatchesAll = false;
					break;                      
				}
			}
			if(bMatchesAll){
				arrReturnElements.push(oElement);
			}
		}
		return (arrReturnElements);
	}

};

vcb.addEvent(window, 'load', vcb.init, false);	// pretty much everything happens at window load
vcb.fixBrowserInconsistenciesPrePage();			// stuff that needs to be done now (in the header) - nothing at this time.
// MSIE requires us to give a "filter: Alpha" style or else the object won't be present. For other browsers,
// this gets us started in the right opacity without having to wait for the init function to run.
document.writeln('<style type="text/css">img#s3logo {-moz-opacity: 0.90; opacity: 0.90; filter: Alpha(opacity=90);}</style>');
