// JavaScript Document
// global flag
var isIE = false;
var siteURL = 'http://www.dacotahbank.com/';
// global request and XML document objects
var req;
var dbCookie = Get_Cookie('dbUser');
var oldLocation = 0;

// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadXMLDoc(url, value, type) {
	if (oldLocation == 0 && dbCookie != null) {
		oldLocation = dbCookie.substring(dbCookie.indexOf("D")+1, (dbCookie.indexOf("D")+2));
	}
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
		switch (type) {
			case 'location':
      			req.onreadystatechange = processReqChange;
				break;
			case 'login':
      			req.onreadystatechange = processELoginChange;
				break;
			case 'myLinkAdd':
      			req.onreadystatechange = processReqChange;
				break;
			case 'myLinkRemove':
      			req.onreadystatechange = processReqChange;
				break;
		}
        req.open("POST", url, true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		switch (type) {
			case 'location':
      			req.send('createCookie=1&oldLoc='+oldLocation+'&dbID='+value);
				break;
			case 'login':
      			req.send('createCookie=1&eLogin='+value);
				break;
			case 'myLinkAdd':
      			req.send('createCookie=1&addMyLink='+value);
				break;
			case 'myLinkRemove':
      			req.send('createCookie=1&removeMyLink='+value);
				break;
		}
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            //req.onreadystatechange = processReqChange;
            req.open("POST", url, true);
			req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			switch (type) {
				case 'location':
      				req.onreadystatechange = processReqChange;
					req.send('createCookie=1&oldLoc='+oldLocation+'&dbID='+value);
					break;
				case 'login':
      				req.onreadystatechange = processELoginChange;
					req.send('createCookie=1&eLogin='+value);
					break;
				case 'myLinkAdd':
      				req.onreadystatechange = processReqChange;
      				req.send('createCookie=1&addMyLink='+value);
					break;
				case 'myLinkRemove':
      				req.onreadystatechange = processReqChange;
      				req.send('createCookie=1&removeMyLink='+value);
					break;
			}
        }
    }
}

// handle onreadystatechange event of req object
function processELoginChange() {
	// only if req shows loading
    if (req.readyState == 1) {
		var newHeading = document.getElementById('eLoginHeading');
		newHeading.innerHTML = 'Loading...';
		var newBody = document.getElementById('eLoginBody');
		newBody.innerHTML = '<p class="login4">&nbsp;<br /><img src="'+siteURL+'images/loadingAnim.gif" /></p>';
	}
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            xmlDisplay();
         } else {
            alert("There was a problem retrieving the XML data:\n"+req.statusText);
         }
    }
}
function processReqChange() {
	// only if req shows loading
    if (req.readyState == 1) {
	}
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            xmlDisplay();
         } else {
            alert("There was a problem retrieving the XML data:\n"+req.statusText);
         }
    }
}


function xmlDisplay() {
	//alert(req.responseText);
	// login test
    //var login = req.responseXML.getElementsByTagName("login");
	if (login = req.responseXML.getElementsByTagName("login")) {
	   for (var i = 0; i < login.length; i++) {
			//alert (getElementTextNS("", "heading", login[i], 0));
			// set new location
			var newHeadingText = getElementTextNS("", "heading", login[i], 0);
			var newHeading = document.getElementById('eLoginHeading');
			newHeading.innerHTML = newHeadingText;
			var newBodyText = getElementTextNS("", "body", login[i], 0);
			var newBody = document.getElementById('eLoginBody');
			newBody.innerHTML = newBodyText;
	   }
	}
	// locations test
   // var locations = req.responseXML.getElementsByTagName("locations");
	if (locations = req.responseXML.getElementsByTagName("location")) {
	   for (var i = 0; i < locations.length; i++) {
			//alert (getElementTextNS("", "location", items[i], 0));
			// set new location
			var newNum = getElementTextNS("", "id", locations[i], 0);
			var newYourDB = document.getElementById('yourDB'+newNum);
			newYourDB.innerHTML = 'Your Dacotah Bank';
			var newSetDB = document.getElementById('setDB'+newNum);
			newSetDB.innerHTML = '';
			// set image properties
			var nameText = getElementTextNS("", "name", locations[i], 0);
			var locationCity = document.getElementById('locationCity');
			locationCity.innerHTML = nameText;
			var imageText = getElementTextNS("", "image", locations[i], 0);
			if (imageText != ' ') {
				MM_swapImage('locationImage','',siteURL+'uploads/'+imageText,1);
			} else {
				MM_swapImage('locationImage','',siteURL+'images/defaultLocation.jpg',1);
			}
			var linkText = getElementTextNS("", "link", locations[i], 0);
			var newLocLink = document.getElementById('locationImageLink');
			newLocLink.href = siteURL+'locations/'+linkText;
			// reset old location
			if (oldNum = getElementTextNS("", "oldLocation", locations[i], 0)) {
				var oldYourDB = document.getElementById('yourDB'+oldNum);
				oldYourDB.innerHTML = '';
				var oldSetDB = document.getElementById('setDB'+oldNum);
				oldSetDB.innerHTML = '<a href="#top" onClick="setLocation(\''+oldNum+'\');">Set as Your Dacotah Bank</a><br />';
			}
			oldLocation = newNum;
	   }
	}
	// mylink test
   // var locations = req.responseXML.getElementsByTagName("locations");
	if (myLinks = req.responseXML.getElementsByTagName("myLinks")) {
	   for (var i = 0; i < myLinks.length; i++) {
			//alert (getElementTextNS("", "location", items[i], 0));
			// set new location
			var newMyLinks = getElementTextNS("", "value", myLinks[i], 0);
			var newMyLinksDiv = document.getElementById('myLinksDiv');
			newMyLinksDiv.innerHTML = newMyLinks;
			var newReq = getElementTextNS("", "changeReq", myLinks[i], 0);
			var newAddLinkDiv = document.getElementById('addLink');
			newAddLinkDiv.innerHTML = newReq;
	   }
	}
}

function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method 
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided 
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            return result.firstChild.nodeValue;    		
        }
    } else {
        return "n/a";
    }
}

function searchFocus(bool) {
	var searchField = document.getElementById('searchField');
	if (bool == true && searchField.value == 'Search DacotahBank.com') {
		searchField.style.color = '#000000';
		searchField.value = '';
	} else if (searchField.value == '') {
		searchField.style.color = '#999999';
		searchField.value = 'Search DacotahBank.com';
	}
}

function addMyLink(id) {
	loadXMLDoc('/xml/myLinksXML.php', id, 'myLinkAdd');
}

function removeMyLink(id) {
	loadXMLDoc('/xml/myLinksXML.php', id, 'myLinkRemove');
}

function setLocation(id) {
	loadXMLDoc('/xml/locationXML.php', id, 'location');
	return false;
}

function setLogin(id) {
	loadXMLDoc('/xml/loginXML.php', id, 'login');
	return false;
}

function Get_Cookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie ()
{	
  var confirmIt = confirm("Are you sure you want to delete your profile?")
  if (confirmIt) {
	  var cookie_name = document.cookie
	  var cookie_date = new Date ( );  // current date & time
	  cookie_date.setTime ( cookie_date.getTime() - 1 );
	  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString() + "; path=/";
	  //document.cookie = "dbUser=V1X16%2C15%2C1%2C34%2C42%2C36";
	  var sURL = unescape(window.location.pathname);
	  window.location = sURL;
  } else { 
  }
}

function alertLeaving ()
{
	return confirm("You are leaving Dacotah Bank Online and will enter another site not associated with Dacotah Bank.");	
}

function alertOk ()
{
	alert("Dacotah Bank has provided this external link for your convenience.");	
}

function alertService () {
	if (confirm("Dacotah Bank has provided this link for your convenience. Dacotah Bank does not control this website and is not responsible for the content, links, privacy policy or security policy of this web site.")) {	
		openAgResources();
	}
}

function alertATM ()
{
	confirm("Dacotah Bank has provided this link for your convenience.");	
}

function alertPrivateComputer ()
{
	return confirm("WARNING:You are about to enter a private computer. Unauthorized access or use is not permitted and constitutes a crime punishable by law.");
}

function atmFocus(bool) {
	var atm = document.getElementById('zipcode');
	if (bool == true && atm.value == 'zip') {
		atm.style.color = '#000000';
		atm.value = '';
	} else if (atm.value == '') {
		atm.style.color = '#999999';
		atm.value = 'zip';
	}
}

function openATMLocations ()
{
	window.open("http://www.allpointnetwork.com/atm/findAtmClosest.do","newWindow","height=600,width=800,resizable=no,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no");
}

function openAgResources ()
{
	window.open("http://www.dacotahbank.com/agmarkets.php","newWindow2","height=800,width=825,resizable=no,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no");
}

function openDebitCard ()
{
	window.open("http://www.dacotahbank.com/debitCard.php","newWindow3","height=800,width=825,resizable=yes,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no");
}

function explainQuickLinks ()
{
	alert("Adding this page to your Favorites allows you to quickly come back to this page from anywhere on the site, while removing it makes room for others to be added.");	
}

function showDepartment(category) {
	document[category+'Slide'].toggle();
}
/* Conflicts with a function in pageContent in asking the questions.
function toggle( targetId, display ){
	target = document.getElementById( targetId );
	if (display == true){
		target.className = 'visible';
		//target.style.display = "block";
	} else {
		target.className = 'invisible';
		//target.style.display = "none";
	}
}*/



function changeArticleDiv(direction, currentDiv) {
	var nextDiv = 0;
	nextDiv = (currentDiv + direction);
	//
	target = document.getElementById( 'currentDiv'+currentDiv );
	target.className = 'invisible';
	target2 = document.getElementById( 'currentDiv'+nextDiv );
	target2.className = 'visible';
}

//get height of a property
function getHeight() {
	var container = document.getElementById("pageArea").scrollHeight;
	var left = document.getElementById("navigation").scrollHeight;
	if (document.getElementById("contentColumn")) {
		var middle = document.getElementById("contentColumn").scrollHeight;
	} else {
		if (document.getElementById("pageContentLocations")) {
			var middle = document.getElementById("pageContentLocations").scrollHeight;
		} else {
			var middle = document.getElementById("questionWrapper").scrollHeight;
		}
	};
	if (document.getElementById("rightSide")) {
		var right = document.getElementById("rightSide").scrollHeight;
	} else {
		var right = 1;
	};
	
	if (left > middle && left > right) {
		var scrollHeight = (left+10);
	} else {
		if (middle > right) {
			var scrollHeight = (middle+10);
		} else {
			var scrollHeight = (right+10);
		};
	};
	document.getElementById("pageArea").style.height = scrollHeight+'px'; 
}

function openHumanResources ()
{
	var location = document.getElementById("locationID").value;
	var position = document.getElementById("positionID").value;
	top.location.href = 'http://www.dacotahbank.com/Human Resources/'+location+'/'+position;
}

function showLocationMap() {
	top.location.href = 'http://www.dacotahbank.com/locations/'+$('locationOptions').value;
}
function sendRequestEmail() {
	alert('onSubmit');
	var log = $('requestText');
	alert('Log');
	$('requestEmailForm').send({ update: log });
	alert('Return');
	return false;
}
//
//
// Begin dynamic checkform area
//
//
//
function checkForm(yourinfo){
	if(yourinfo.firstName.value =="" || yourinfo.firstName.value == null){
		alert("Please enter your first name");
		return(false);
	}
	
	if(yourinfo.lastName.value =="" || yourinfo.lastName.value == null){
	alert("Please enter your last name");
	return(false);
	}
	
	if(yourinfo.address.value =="" || yourinfo.address.value == null){
		alert("Please enter your address");
		return(false);
	}

	if(yourinfo.city.value =="" || yourinfo.city.value == null){
		alert("Please enter your city");
		return(false);
	}

	if(yourinfo.state.value =="" || yourinfo.state.value == null){
		alert("Please enter your state");
		return(false);
	}

	if(yourinfo.zip.value =="" || yourinfo.zip.value == null){
		alert("Please enter your zip code");
		return(false);
	}
	
	if(yourinfo.email.value =="" || yourinfo.email.value == null){
		alert("Please enter your email address");
		return(false);
	}

	if(yourinfo.interest.value =="Select" || yourinfo.interest.value =="Please choose one"){
		alert("Please enter your financing preference");
		return(false);
	}

	if(!yourinfo.emailchoice[0].checked && !yourinfo.emailchoice[1].checked){
		alert("Please check yes or no to whether you'd like to receive occasional information about real estate financing programs and promotional rate offers via email");
		return(false);
	}
	
	
	else{
		return(true);
	}
	
}
//
//
//
function checkForm2(yourinfo){
	if(yourinfo.showLocation.value =="noneSelected" || yourinfo.showLocation.value =="Select one"){
		alert("Please select which home show you attended");
		return(false);
	}
	
	if(yourinfo.firstName.value =="" || yourinfo.firstName.value == null){
		alert("Please enter your first name");
		return(false);
	}
	
	if(yourinfo.lastName.value =="" || yourinfo.lastName.value == null){
	alert("Please enter your last name");
	return(false);
	}
	
	if(yourinfo.address.value =="" || yourinfo.address.value == null){
		alert("Please enter your address");
		return(false);
	}

	if(yourinfo.city.value =="" || yourinfo.city.value == null){
		alert("Please enter your city");
		return(false);
	}

	if(yourinfo.state.value =="" || yourinfo.state.value == null){
		alert("Please enter your state");
		return(false);
	}

	if(yourinfo.zip.value =="" || yourinfo.zip.value == null){
		alert("Please enter your zip code");
		return(false);
	}

	if(yourinfo.email.value =="" || yourinfo.email.value == null){
		alert("Please enter your email address");
		return(false);
	}

	if(yourinfo.dayphone.value =="" || yourinfo.dayphone.value == null){
		alert("Please enter your daytime phone number");
		return(false);
	}
	
	if(yourinfo.interest.value =="Select" || yourinfo.interest.value =="Please choose one"){
		alert("Please enter your financing preference");
		return(false);
	}

	if(!yourinfo.emailchoice[0].checked && !yourinfo.emailchoice[1].checked){
		alert("Please click yes or no to whether you'd like to receive occasional information about real estate financing programs and promotional rate offers via email");
		return(false);
	}
	else{
		return(true);
	}
	
}
//
//
//
function checkForm3(yourinfo){
	if(!yourinfo.mediaPath[0].checked && !yourinfo.mediaPath[1].checked && !yourinfo.mediaPath[2].checked && !yourinfo.mediaPath[3].checked){
		alert("Please select how you heard about us");
		return(false);
	}
	
	if(!yourinfo.farm1.checked&& !yourinfo.farm2.checked && !yourinfo.farm3.checked && !yourinfo.farm4.checked && !yourinfo.farm5.checked && !yourinfo.farm6.checked && !yourinfo.farm7.checked && !yourinfo.farm8.checked && !yourinfo.farm9.checked){
		alert("Please select all the descriptions that apply to your farm or ranch");
		return(false);
	}
	
	if(yourinfo.firstName.value =="" || yourinfo.firstName.value == null){
		alert("Please enter your first name");
		return(false);
	}
	
	if(yourinfo.lastName.value =="" || yourinfo.lastName.value == null){
	alert("Please enter your last name");
	return(false);
	}
	
	if(yourinfo.address.value =="" || yourinfo.address.value == null){
		alert("Please enter your address");
		return(false);
	}

	if(yourinfo.city.value =="" || yourinfo.city.value == null){
		alert("Please enter your city");
		return(false);
	}

	if(yourinfo.state.value =="" || yourinfo.state.value == null){
		alert("Please enter your state");
		return(false);
	}

	if(yourinfo.zip.value =="" || yourinfo.zip.value == null){
		alert("Please enter your zip code");
		return(false);
	}

	if(yourinfo.email.value =="" || yourinfo.email.value == null){
		alert("Please enter your email address");
		return(false);
	}

	if(yourinfo.dayphone.value =="" || yourinfo.dayphone.value == null){
		alert("Please enter your daytime phone number");
		return(false);
	}

//	if(yourinfo.emailchoice2.value =="" || yourinfo.emailchoice2.value == null){
//		alert("Please click yes or no to whether you'd like to receive occasional information about real estate financing programs and promotional rate offers via email");
//		return(false);
//	}
	if(!yourinfo.emailchoice[0].checked && !yourinfo.emailchoice[1].checked){
		alert("Please click yes or no to whether you'd like to receive occasional emails about bank promotions related to your operation");
		return(false);
	}
	else{
		return(true);
	}
	
}
//
//
//
//Begin dynamic radio button area
//
//
function switchDiv(div_id)
{
  var style_sheet = getStyleObject(div_id);
  if (style_sheet)
  {
    hideAll();
    changeObjectVisibility(div_id,"visible");
  }
  else 
  {
    alert("sorry, this only works in browsers that do Dynamic HTML");
  }
}

// function hideAll()
//  hides a bunch of divs
//
function hideAll()
{
   changeObjectVisibility("web","hidden");
   changeObjectVisibility("show","hidden");
}

// function getStyleObject(string) -> returns style object
//  given a string containing the id of an object
//  the function returns the stylesheet of that object
//  or false if it can't find a stylesheet.  Handles
//  cross-browser compatibility issues.
//
function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  //
  if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {  
	return document.all(objectId).style;
   } 
   else if (document.layers && document.layers[objectId]) { 
	return document.layers[objectId];
   } else {
	return false;
   }
}

function changeObjectVisibility(objectId, newVisibility) {
    // first get a reference to the cross-browser style object 
    // and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
}


