//addTitleAttribute(parentId:String[HTML element ID], elem:String[HTML element], truncateDate:Boolean[true or false], truncateLength:String[# of characters to limit])
function addTitleAttribute(parentId, elem, truncateData, ellipseLength){
//if the parentId does not exist, do not execute
if (!document.getElementById(parentId)){
	return;
}
var elemToTitle = document.getElementById(parentId).getElementsByTagName(elem);

	for (var i = 0; i < elemToTitle.length; i ++){
		if(elemToTitle[i].innerHTML.length == 0){
			//add non breaking space if the element is empty
			elemToTitle[i].innerHTML = '&nbsp;';
		}else if(elemToTitle[i].innerHTML.indexOf('<img') != -1 || elemToTitle[i].innerHTML.indexOf('<IMG') != -1){
			elemToTitle[i].firstChild.setAttribute('title', elemToTitle[i].firstChild.getAttribute('alt'));
		}else{
			elemToTitle[i].title = elemToTitle[i].innerHTML;
			if(truncateData == true || truncateData == 'true'){
				//alert(typeof(truncateData));
				elemToTitle[i].innerHTML = ellipseString(elemToTitle[i].innerHTML, ellipseLength);
			}
		}
	}
}

function ellipseString(strng, ellipseLength){
	if (strng.length > ellipseLength){
		strng = strng.substring(0, ellipseLength);
    	//this will truncate after the last space of a whole word within the length limit
		//strng = strng.replace(/\w+$/, '');
		return strng + '...';
	} else {
		return strng;
	}	
}

//alternating rows work by selecting a parent id element and then get applied to any element by tag name inside the parent id.
function ledgerRowColors(parentId, elem, colorOne, colorTwo){
//if the parentId does not exist, do not execute
if (!document.getElementsByTagName) return false;

if (!document.getElementById(parentId)){
	return;
}else{
	
 	var elemRows = document.getElementById(parentId).getElementsByTagName(elem);
		for(var i = 0; i < elemRows.length; i++){
			if(i % 2){
				elemRows[i].style.backgroundColor = colorOne;
			}else{
				elemRows[i].style.backgroundColor = colorTwo;
			}
		} 
	}
}

//adds alternating classes to a series of child elements (such as table rows)
//accepts id of parent, element name (such as tr), and two class names
//remember to add these classes to your css in order to apply styling
//created 6/4/2009 - KC
function legerRowClasses(id, elem, oddClass, evenClass){
  if(document.getElementsByTagName){  
    var table = document.getElementById(id);  
    var rows = table.getElementsByTagName(elem);  
    for(var i = 0; i < rows.length; i++){          
      if(i % 2 == 0){
        rows[i].className = evenClass;
      }else{
        rows[i].className = oddClass;
      }      
    }
  }
  else{
    return false;
  }
}

var Ajax = {
	loadFile:function(filename, element){
		if(filename.indexOf("?") == -1){
			var filename = filename + "?nocache=" + new Date().getTime();
		} else{
			var filename = filename + "&nocache=" + new Date().getTime();
		}
			//alert(filename)
		var request = this.getHTTPObject();
		if (request) {
			request.onreadystatechange = function() {
			Ajax.displayResponse(request, element);
		}
		request.open("GET", filename, true);
		request.setRequestHeader("Content-Type", "text/html");
		request.send(null);
	}
},
	
	getHTTPObject:function(){
		var xhr = false;
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		} 
	}
		return xhr;
},

	displayResponse:function(request, element) {
		if (request.readyState == 4) {
			if (request.status == 200 || request.status == 304) {
				var content = request.responseText;
				//alert(content);
				var elem = document.getElementById(element);
				elem.innerHTML = content;
				
			}
		}
	}
}

var ux = {
	transSite : function (){
		//used to check if customer is logged in when on static page or from static popup page when logged in
        
		if((top.loggedIn && top.loggedIn == 'true')){
				////alert('logged in self');
				return	true;
		//if the loggedIn variable exists on an opener	and not the pop-up page	
		}else if( window.opener && !top.loggedIn){
			//if loggedIn variable is present in the opener
				if(window.opener.loggedIn == 'true'){
					////alert('parent > logged in');
					return true;	
				}else{
					////alert('parent > not logged in');
					return false;	
				}
		} else {
			////alert('not logged in on self or opener');
			return false;
		}
	},
	eoCustomer : function (){    
		if (top.hasEO =='true'){
			return true;
		} else {
			return false;	
		}
	},
	//must be include with a window.onload on the page where to be used.
	showHideTransRelatedElems : function(condition, tag, elemClassName) {
		//alert('condition: ' + condition + '  tag: ' + tag + '  class: ' + elemClassName)
		if ( condition ) {
			//if user is logged in hide nothing
			return;
		} else {
			//hide elements if loggedin and element has a class are specified
			var shLinks = document.getElementsByTagName(tag);
			for (var i = 0; i < shLinks.length; i++) {
				if ( shLinks[i].className == elemClassName ||  shLinks[i].className.indexOf(elemClassName) != -1) {
					shLinks[i].style.display = 'none';
				}
			}
		}
	},
	//use this to conditionally check static trans links to different pages (not pop-up application)
	//this also works with multiple classes attached.
	staticTransLinkRedirect : function(elemClassName){
		var redirLink = document.getElementsByTagName('a');
		
		for (var i = 0; i < redirLink.length; i++){
			if ( redirLink[i].className == elemClassName ||  redirLink[i].className.indexOf(elemClassName) != -1 ){
				
				var defaultLink = redirLink[i].getAttribute('href');
				var loggedInLink = redirLink[i].getAttribute('trans');
					if ( ux.transSite() ){
						redirLink[i].setAttribute('href', loggedInLink);
						redirLink[i].setAttribute('target', "_top");
					}else{
						redirLink[i].setAttribute('href', defaultLink);
						redirLink[i].setAttribute('target', "_top");
					}
			}
		}
	}
		
		
//close object literal	
};


function checkEO(){
	//logged in        
	if ( ux.transSite() ){
		//has an EO 
		if( ux.eoCustomer() ){
			//show link to previous rates
			if( document.getElementById('rateTable') ){
				document.getElementById('rateTable').style.display = 'block';
				document.getElementById('eoBtn').style.display = "none";
				return;
			}
			var startText = document.createTextNode("Start Today");
			document.getElementById('eoBtn').style.display = "block";
			document.getElementById('btnText').innerHTML ="";
			document.getElementById('btnText').appendChild(startText);
			document.getElementById('userLink').setAttribute('href', 'https://secure.ingdirect.com/myaccount/INGDirect/bill_pay.vm');
			document.getElementById('userLink').setAttribute('title', 'Start Today');
			document.getElementById('userLink').setAttribute('target', '_top');
			return;
		}else{
			//just show 'apply now' button
			var applyText = document.createTextNode("Apply Now");
			document.getElementById('eoBtn').style.display = "block";
			document.getElementById('btnText').innerHTML="";
			document.getElementById('btnText').appendChild(applyText);
			document.getElementById('userLink').setAttribute("href", "https://secure.ingdirect.com/myaccount/INGDirect.html?command=gotoOpenOCA");
			document.getElementById('userLink').setAttribute('title', "Apply Now");
			document.getElementById('userLink').setAttribute('target', '_top');
			return;
		}
	//not loggedin show 'apply now' button
	} else {
		var applyText = document.createTextNode("Apply Now");
		document.getElementById('eoBtn').style.display = "block";
		document.getElementById('btnText').innerHTML="";
		document.getElementById('btnText').appendChild(applyText);
		document.getElementById('userLink').setAttribute("href", "https://banking.ingdirect.com/savings/initial.vm?type=4000");
		document.getElementById('userLink').setAttribute('title', "Apply Now");
		var eoElm = document.getElementById('userLink');
			document.getElementById('userLink').onclick = function(){
					popUp.application(this.href);return false;
					urchinTracker( this.urchin );
					
					return false;
					}
	}
}

function applyUrchinTracker( elemClassName ){
	var urchinLnks = document.getElementsByTagName('a');
	
	
	
	for (var i = 0; i <  urchinLnks.length; i++){
			if (  urchinLnks[i].className == elemClassName || urchinLnks[i].className.indexOf(elemClassName) != -1 ){
				
					
				var uLnk = urchinLnks[i].getAttribute('urchin')
			
				//urchinLnks[i].onclick = urchinTracker( pgView );
				urchinLnks[i].onclick = function(){
					urchinTracker( uLnk );
				}
			}
	}
}


function checkEOBP(){
	//logged in        
	if ( ux.transSite() ){
		document.getElementById('eobpBtn').style.display = "block";
		document.getElementById('learnBtn').style.float = "left";
		document.getElementById('learnBtn').style.clear = "none";
		document.getElementById('learnBtn').style.marginLeft = "60px";
		document.getElementById('btnText').innerHTML ="";
		
		//has an EO 
		if( ux.eoCustomer() ){
			//show link to previous rates
			var payBillText = document.createTextNode("Pay A Bill");
			document.getElementById('btnText').appendChild(payBillText);
			document.getElementById('userLink').onclick = function() {
				urchinTracker("BPSweep_eocust_pay");
			}
			
			document.getElementById('userLink').setAttribute('href', 'https://secure.ingdirect.com/myaccount/INGDirect/bill_pay.vm');
			document.getElementById('userLink').setAttribute('title', 'Pay A Bill');
			document.getElementById('userLink').setAttribute('target', '_top');
			document.getElementById('bpPara').style.display = "block";
			
			
			return;
		}else{
			//just show 'apply now' button
			var applyText = document.createTextNode("Apply Now");
			document.getElementById('btnText').appendChild(applyText);
			
			document.getElementById('userLink').onclick = function() {
				urchinTracker("BPSweep_INGcust_app");
			}
			
			document.getElementById('userLink').setAttribute("href", "https://secure.ingdirect.com/myaccount/INGDirect.html?command=gotoOpenOCA");
			document.getElementById('userLink').setAttribute('title', "Apply Now");
			document.getElementById('userLink').setAttribute('target', '_top');
			document.getElementById('noneocust').style.display = "block";
			return;
		}
	//not loggedin show 'apply now' button
	} else {
			document.getElementById('uiElems').style.textAlign = "center";
			document.getElementById('noneocust').style.display = "block";
			
			document.getElementById('userLink').onclick = function(){
					
					popUp.application(this.href);return false;
					urchinTracker("BPSweep_noncust_app");
					
					
		return false;
		};
			return;
		return;
	}
}

//this executes individual elements based on class for static/trans pop-up application
function setAllDynamicLinks(){
	var lnks = getElementsByClassName('dLink', 'a');
	for (var i = 0; i < lnks.length; i++){
		setLinkAttributes(lnks[i]);
	}
}


//this executes individual elements based on ID for static/trans pop-up application
function setIndividualDynamicLink(){
	var conditionalLink = document.getElementById('userLink');
	setLinkAttributes(conditionalLink);
}

function setLinkAttributes(elem){
	//the default link (href attrib) for the application.
	//this will degrade if js is turned off by going to the link instead of a pop-up
	var defaultLink = elem.getAttribute('href');
	
	//grab the alternate link for logged in (trans attrib)
	var loggedInLink = elem.getAttribute('trans');

	//check to see if user is in the frameset and is logged in.
	if( ux.transSite() )	{
		elem.setAttribute('href', loggedInLink);
		elem.setAttribute('target', "_top");
	} else	{
		elem.onclick = function(){
		popUp.application(elem.href);
		return false;
		};
	}
}

function linkSelector(){
var ls = document.getElementById( 'linkSelect' );
//assign trans attribute value
linkSel = ls.getAttribute( 'trans' );
var urlStr = new String( parent.location );

//if user is logged in or https://secure, dynamically update the href attribute to the trans attribute value
	if( ux.transSite() || urlStr.indexOf( 'https://secure.ingdirect.com' ) == 0 ){
		ls.setAttribute('href', linkSel );
	}
}

function getTodaysDateNumeric(){
	var today = new Date();
	var month = today.getMonth() + 1;
	var day = today.getDate();
	var year = today.getYear();
	if(year < 1000) year += 1900;
	
	return month + "/" + day + "/" + year;
}

function getDateStr(){
    var today = new Date();
    var year = today.getYear();
    if(year < 1000) year += 1900;
    var todayStr = GetMonth(today.getMonth()) + " " + today.getDate();
    todayStr += ", " + year;
    return todayStr;
}
	
function GetMonth(intMonth){
    var MonthArray = new Array("January", "February", "March",
                               "April", "May", "June",
                               "July", "August", "September",
                               "October", "November", "December") 
    return MonthArray[intMonth] 	  	 
    }


var popUp = {
	 // Window position and size
	x:0,
	y:0,

    	application: function(url) {
			w = 680;
			h = 775;
			popUp.opener(url, w, h, true);
        
    },
		solutionsCalc: function(url) {
			scw = 720;
			sch = 820;
			popUp.opener(url, scw, sch);
       
	},
		demo: function(url) {
			dw = 920;
			dh = 630;
			popUp.opener(url, dw, dh);
       
	},
		demoEO: function(url) {
			dw = 570;
			dh = 340;
			popUp.opener(url, dw, dh);
       
	},
		newWindow: function(url, vh, vw) {
			popUp.opener(url, vw, vh, false, true);
       
	},
		mortgageApp: function(url) {
			maw = 720;
			mah = 900;
			popUp.opener(url, maw, mah);
        
	},
		shareBuilderSpeedBump: function(url) {
				sbw = 650;
				sbh = 400;
				popUp.opener(url, sbw, sbh);
		  
	},
		eoRateTable: function(url) {
				eotablew = 400;
				eotableh = 245;
				popUp.opener(url, eotablew, eotableh);
		  
	},
		helpCenter: function(url) {
		hcw = 640;
		hch = 480;
		var authURL = new String();
		if(ux.transSite()){
        	if( url.indexOf( '?' ) != -1 ){
				var splitURL = url.split('?');
				authURL = splitURL[0] + '?isAuthenticatedUser=1&' + splitURL[1];
        		popUp.opener(authURL, hcw, hch, false, true);
				return true;
			}else if( url.indexOf('?') == -1 ){
				authURL = url.substring( 0, url.lastIndexOf('/') ) + '?isAuthenticatedUser=1';
        		popUp.opener(authURL, hcw, hch, false, true);
			}else{
        		return;
			}
		}else{
        	popUp.opener(url, hcw, hch, false, true);
		}
	},
		opener: function(url, w, h, toolbar, scrollbar){
			popUp.x = (screen.width - w)/2;
			popUp.y = (screen.height - h)/2;
			var appFeatures = new String( 'toolbar,titlebar,status,location,menubar,resizable,scrollbars,width=' + w + ',height=' + h )
			var features = new String( 'resizable,width=' + w + ',height=' + h )
			var scrollFeatures = new String( 'resizable,scrollbars,width=' + w + ',height=' + h )
			if(toolbar){ //popup with full controls
				popUp.win = window.open(url, "popup", appFeatures);
				return false;
			} else if(scrollbar){ //popup with scrollbars only
			  popUp.win = window.open(url, "popup", scrollFeatures);
			  return false;				 
			} else { //popup no scroll or controls
				popUp.win = window.open(url, "popup", features);
        return false;
			}
		}
	
}




function roundMoney(x) {
	var scale = Math.pow(10, 2);
	var valString = "" + Math.round(x * scale) / scale;

	if (valString.length == 1) {
		valString += ".00";
	}
	else if (valString.length == 3) {
		valString += "0";
	}
	return valString;
}

function injectDate(){
	var newYear = new Date();
	currYear = newYear.getYear();

	//Mozilla, Opera, Safari
	if (document.addEventListener)	{
		document.getElementById('dynamic_date').innerHTML = 2000 + (currYear - 100);
	
	//non-standard browsers (ie)
	}else{
		document.getElementById('dynamic_date').innerHTML = currYear;
	}
}

//Usage: addEvent(window, 'onload', new Function([function code]));
function addEvent(elm, evtName, evtFunc){
 if (elm.addEventListener) {
  elm.addEventListener(evtName.substr(2), evtFunc, false);
 } else if (elm.attachEvent) {
  elm.attachEvent(evtName, evtFunc);
 } else {
  elm.setAttribute(evtName, evtFunc);
 } 
}

function setDomain(){
	if(document.domain != 'ingdirect.com')
		document.domain = 'ingdirect.com';
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}




function openPopUp(url, winName, winFeatures){
	var pop = window.open(url,winName,winFeatures);
	pop.focus();
}


function openPopWindow(theURL, winName, features) { //v2.0
  window.open(theURL, winName, features);
}


//Highlights the Navigation Ball associated with the href when inside the TranSite Frame
function setSelectedNav(href){
	setDomain();
	if(top.loggedIn){
		var frameSrc = "https://secure.ingdirect.com/myaccount/StaticContent.html?page=left&link=";
		switch(getSection(href))
		{
			case "OPEN":
				var number = "2"
				break;
			case "PRODUCTS":
				var number = "3"
				break;
			case "PRIVACY":
				var number = "4"
				break;
			case "ABOUT":
				var number = "5"
				break;
			case "FAQS":
				var number = "6"
				break;
			default:
				break;			
		}
		window.parent.left.location = frameSrc + number;
	}
}
//Returns the section associated with the href in Caps or NULL if the href is invalid
function getSection(href){
	var extLoc = href.search(/.asp/);
	if(extLoc != -1){
		var hrefSplit = href.substring(0,extLoc).split('/');
		var section = hrefSplit[hrefSplit.length - 1];
		return section.toUpperCase();
	}
	else{
		return null;
	}
}
//Takes in a from URL and a to URL and switches the highlighted ball on the TranSite Navigation if necessary (Used in SpeedBump Pages)
function adjustNav(from, to){
	setDomain();
	if(top.loggedIn){
		var fromSection = getSection(from);
		var toSection = getSection(to);
		if(toSection != null && (fromSection == null ||  (fromSection != toSection)))
		{
			setSelectedNav(to);
		}
	}
}

function redirectParent(url){
	try{
		if(window.opener.location.href.indexOf("https") != -1)
			window.opener.location = url + "&NF=false";
		else
			window.opener.location = url;
		this.close();
		window.opener.focus();
		return false;
	}
	catch(err){
		this.close();
		return true;
	}
}