/**
 * General purpose functions that should be used to maintain cross-browser
 * compatibility
 */


/********* Set functions for page boundaries ************/
function setLeftOfPage(value) {
   if (navigator.appName == "Netscape") {
      window.pageXOffset = value;
   }else{
      document.body.scrollLeft = value;
   }
}

function setPageHeight(value) {
   if (navigator.appName == "Netscape") {
      window.innerHeight = value;
   }else{
      document.body.clientHeight = value;
   }
}

function setPageWidth(value) {
   if (navigator.appName == "Netscape") {
      window.innerWidth = value;
   }else{
      document.body.clientWidth = value;
   }
}

function setTopOfPage(value) {
   if (navigator.appName == "Netscape") {
      //alert("setTopOfPage");
      /******** ??? *********/
      //window.pageYOffset = value;
   }else{
      document.body.scrollTop = value;
   }
}

function setLeftOfPage(value) {
   if (navigator.appName == "Netscape") {
      window.pageXOffset = value;
   }else{
      document.body.scrollLeft = value;
   }
}

function setPageHeight(value) {
   if (navigator.appName == "Netscape") {
      window.innerHeight = value;
   }else{
      document.body.clientHeight = value;
   }
}

function setPageWidth(value) {
   if (navigator.appName == "Netscape") {
      window.innerWidth = value;
   }else{
      document.body.clientWidth = value;
   }
}

/********* Get functions for page boundaries ************/
function getLeftOfPage() {
   if (navigator.appName == "Netscape") {
      return window.pageXOffset;
   }else{
      return document.body.scrollLeft;
   }
}

function getPageHeight() {
   if (navigator.appName == "Netscape") {
      return window.innerHeight;
   }else{
      return document.body.clientHeight;
   }
}

function getPageWidth() {
   if (navigator.appName == "Netscape") {
      return window.innerWidth;
   }else{
      return document.body.clientWidth;
   }
}

function getTopOfPage() {
   if (navigator.appName == "Netscape") {
      return window.pageYOffset;
   }else{
      return document.body.scrollTop;
   }
}

function getLeftOfPage() {
   if (navigator.appName == "Netscape") {
      return window.pageXOffset;
   }else{
      return document.body.scrollLeft;
   }
}

function getPageHeight() {
   if (navigator.appName == "Netscape") {
      return window.innerHeight;
   }else{
      return document.body.clientHeight;
   }
}

function getPageWidth() {
   if (navigator.appName == "Netscape") {
      return window.innerWidth;
   }else{
      return document.body.clientWidth;
   }
}

/**
 * Retrieve an object regardless of what browser you are using
 */
function getForm(formName) {
   if(document.getElementById && document.getElementById(formName)) {
      return document.getElementById(formName);
   } else if (document.all && document.all(formName)) {
      return document.all(formName);
   } else if (document.forms) {
      if(document.forms[formName]) {
         return document.forms[formName]
      } else {
         return nsGetForm(formName);
      }
   } else {
      alert("returning false (fell through getForm(\""+formName+"\") )");
      return false;
   }
}

/**
 * Retrieve an object regardless of what browser you are using
 */
function getFormObject(formName,objectId) {
   var obj;
   if (document.forms) {
      var form;
      if( (form=document.forms[formName]) ) {
         obj=form.elements[objectId];
      }
   } else {
      alert("We are sorry. Your Browser may not support the features needed to use this site properly.");
   }
   return obj;
}
/*
function printFormObjects(formName) {
   var message = "";
   var objects = new Array();
   var form = document.forms[formName];
   if(!form) {
      message = "Form name "+formName+" not found!";
   } else {
      for(i=0;i<form.length;i++) {
         objects[i] = form[i].name;
      }
      var sortedObjects = objects.sort();
      for(i=0;i<sortedObjects.length;i++) {
         message += sortedObjects[i] + ", ";
      }
   }
}

/**
 * Retrieve an object regardless of what browser you are using
 * (Such as a <div>)
 */
function getObject(objectId) {
   var obj = false;
   if(document.getElementById) {
      obj=document.getElementById(objectId);
   } else {
      alert("Browser incompatibility: Please contact \x4c\x61\x77\x44\x65\x70\x6f\x74\x54\x65\x63\x68\x48\x65\x6c\x70\x40\x6c\x61\x77\x64\x65\x70\x6f\x74\x2e\x63\x6f\x6d for assistance.\n\nWe apologize for the inconvenience.");
   }
   return obj;
}
/**
 * Set visibility / display property.  We will use both at the same time.
 * second parameter should be boolean
 */
function setVisDisp(objectId,visible) {
   if(document.getElementById && document.getElementById(objectId)) {
      if(visible) {
         document.getElementById(objectId).style.visibility = "visible";
         document.getElementById(objectId).style.display = "block";
      } else {
         document.getElementById(objectId).style.visibility = "hidden";
         document.getElementById(objectId).style.display = "none";
      }
   } else if (document.all && document.all(objectId)) {
      if(visible) {
         document.all(objectId).style.visibility = "visible";
         document.all(objectId).style.display = "block";
      } else {
         document.all(objectId).style.visibility = "hidden";
         document.all(objectId).style.display = "none";
      }
   } else if (document.layers) {
      if(document.layers[objectId]) {
         if(visible) {
            document.layers[objectId].visibility = "show";
            document.layers[objectId].display = "block";
         } else {
            document.layers[objectId].visibility = "hide";
            document.layers[objectId].display = "none";
         }
      } else {
         // As this layer may be embedded, we have to traverse
         // the tree to find it.
         var retval= nsGetLayer(document.layers,objectId);
         if(retval) {
            if(visible) {
               retval.visibility = "show";
               retval.display = "block";
            } else {
               retval.visibility = "hide";
               retval.display = "none";
            }
         }
         /*
         var theString = "document.layers.length = "+document.layers.length+"\n\n";
         var i = 0;
         for(i=0;i<document.layers.length;i++) {
            theString += document.layers[i].name+"\n";
         }
         alert(theString);
         */
      }
   }
}

/**
 * Get visibility / display property.  We will use both at the same time.
 */
function getVisDisp(objectId) {
   if(document.getElementById && document.getElementById(objectId)) {
      if(document.getElementById(objectId).style.visibility == "visible") {
         return true;
      } else {
         return false;
      }
   } else if (document.all && document.all(objectId)) {
      if(document.all(objectId).style.visibility == "visible") {
         return true;
      } else {
         return false;
      }
   } else if (document.layers && document.layers[objectId]) {
      if(document.layers[objectId].visibility == "show") {
         return true;
      } else {
         return false;
      }
   } else {
      return false;
   }
}

/**
 * Get the style of an object regardless of browser
 */
function getStyleObject(objectId) {
   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 setStatus(msg) {
   window.status = msg;
}

function bookmark(){
   window.external.AddFavorite(window.location.href,window.document.title);
}

/* These two functions are for disabling selection in Netscape */
function disableselect(event) {
   return false;
}

function enableselect(event) {
   return false;
}

//Following functions are common cookie fucntions
// this function gets the cookie, if it exists
function GetCookie( 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 ) );
}
/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function SetCookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function DeleteCookie( name, path, domain ) {
	if ( GetCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function addEvent( obj, type, fn ) {
        if( obj.attachEvent ) {
                obj["e"+type+fn] = fn;
                obj[type+fn] = function(){obj["e"+type+fn]( window.event );}
                obj.attachEvent( "on"+type, obj[type+fn] );
        } else
                obj.addEventListener( type, fn, true );
}
function removeEvent( obj, type, fn ) {
        if( obj.detachEvent ) {
                obj.detachEvent( "on"+type, obj[type+fn] );
                obj[type+fn] = null;
        } else
                obj.removeEventListener( type, fn, false );
}

// This adds an event to Site Catalyst.
function addSiteCatalystEvent(eventName){
   if(typeof(s) != 'undefined'){
      if(s.events.indexOf(eventName)<0){
         if(s.events != ""){
            s.events += ",";
         }
         s.events+=eventName;
         s.t();
      }
   }
}
var setFocus = false;
function setFocusValidator(source) {
	var js = 'var obj = document.getElementById(' + source.id + '.controltovalidate); if (obj) { obj.focus(); }';
	eval(js); 
    if(setFocus == false){
		setFocus = true;
	}
}
function isArray(obj) {
	if (obj.constructor.toString().indexOf('Array') == -1)
		return false;
	else
		return true;
}
function cf(action) {
	var f = document.createElement('FORM');
	f.method='POST';
	f.action=action;
	if(arguments[1]) f.target='_blank';
	document.body.appendChild(f);
	return f;
}
function cfi(parentForm,name,value) 
{
	var i = document.createElement('INPUT');
	i.type='hidden';
	i.name=name;
	i.value=value;
	parentForm.appendChild(i);
}
function postTo(url) 
{
	var f = cf(url,arguments[2]);
	var v = arguments[1];
	for(var n in v) cfi(f,n,v[n]);
	f.submit();
	return false;
}
function postLink(a) {
   var SID;
   postTo(a.href,{"SID":SID},arguments[1]);
}
var contentFixed=false;
function getStyle(el,styleProp){
	if (el.currentStyle)
		var y = el.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
	return y;
}
function fixContent() {
   if(contentFixed) return;
   var ct=getObject("contentTop");
   if(ct!=null) return;
   var c=getObject("content");
   if(c==null) return;
	var w=getObject("wrapper");
   if(w==null) return;
   ct=document.createElement("DIV"); 
   ct.id="contentTop";
   var h=c.innerHTML;
   c.innerHTML="";
   ct.innerHTML=h;
   c.appendChild(ct);
   var ce=document.createElement("DIV");
   ce.id="contentEnd";
   c.appendChild(ce);
   contentFixed=true;
   var n=getObject("navigation");
   if(n==null || (getStyle(n,"display")=="none")) w.className += " noNav";
} //function fixContent()
//fixContent();
addEvent(window, 'load', fixContent);

function isOrderOrProductSelectionPage() {
	var url = top.location.href.toLowerCase();
	var d1, d2, d3;
	if((d1 = url.indexOf('dcsmain')) != -1 && 
		(d2 = url.indexOf('dcsdefinitions', d1)) != -1 &&
		(d3 = url.indexOf('order', d2)) != -1 &&
		url.indexOf('xml', d3) != -1) {
		return true;
	}
	if(url.indexOf('/contracts/order') != -1)
		return true;
	return false;
}
function rewriteFooterLinks() {
	if(isOrderOrProductSelectionPage()) {
		var footer = getObject('footer');
		var tags = footer.getElementsByTagName('A');
		for(var i=0; i<tags.length; i++) {
			tags[i].target = '_blank';
		}
	}
}
addEvent(window, 'load', rewriteFooterLinks);

/* Read the site.xml config for JavaScript 
 * Author: Chris Poirier
 * Date: October 4, 2011
 */
var __CONFIG;
// Set the configuration
function __setConfig() {
	if(!__CONFIG) {
		var brand = GetCookie('brand');
		if(!brand) brand = '';
		var technology = __getTechnology();
		__readConfig(brand, technology);
	}
}
// Get the technology of the page
function __getTechnology() {
	// Check for aspnetForm
	if(document.forms['aspnetForm'])
		return '.NET';
	// Check for __VIEWSTATE
	if(document.forms[0] && document.forms[0].elements['__VIEWSTATE'])
		return '.NET';
	// If aspnetForm and __VIEWSTATE don't exists, then we are on PHP
	return 'PHP';
}
// Read the configuration from site.xml using the given brand and technology
function __readConfig(brand, technology) {
	// Read the XML
	var xmlHTTP;
	if(window.XMLHttpRequest)
		xmlHTTP = new XMLHttpRequest();
	else
		xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	xmlHTTP.open("GET", "/common/xml/site.xml.php", false);
	xmlHTTP.send();
	var xmlDoc = xmlHTTP.responseXML;
	if(xmlDoc.normalize) xmlDoc.normalize();
	var configuration = xmlDoc.getElementsByTagName("configuration")[0];

	// Find the host node
	var hosts = configuration.getElementsByTagName("hosts")[0];
	var host = __getChildElementByAttribute(hosts, 'host', 'name', document.location.hostname);

	if(host != null) {
		// Do not continue if the node is a redirect
		var redirect = host.getElementsByTagName("redirect");
		if(redirect.length == 0) {
			// Read the host configuration
			__CONFIG = {};
			__readConfigSettings(host, brand, technology);

			// Find the family node
			var families = configuration.getElementsByTagName("site_families")[0];
			var family = __getChildElementByAttribute(families, "site_family", "name", __CONFIG["site_family"]);

			// Read the family configuration
			if(family != null)
				__readConfigSettings(family, brand, technology);
		}
	}
}
// Get the child element of the given parent with the given element name
// where the given attribute equals the given value.
function __getChildElementByAttribute(parentElement, elementName, attrName, attrValue) {
	var elements = parentElement.getElementsByTagName(elementName);
	for(var i=0; i<elements.length; i++) {
		if(elements[i].attributes.getNamedItem(attrName).value == attrValue)
			return elements[i];
	}
	return null;
}
// Read the configuration settings from the given parent
function __readConfigSettings(parentElement, brand, technology) {
	var elements = parentElement.getElementsByTagName("*");
	for(var i=0; i<elements.length; i++) {
		if(elements[i].parentNode.nodeName == parentElement.nodeName) {
			// If the element has a technology attribute, check that it contains the current technology
			if(elements[i].attributes.getNamedItem('technology')) {
				var technologies = elements[i].attributes.getNamedItem('technology').value.toUpperCase().split(',');
				var hasTechnology = false;
				for(var j=0; j<technologies.length; j++) {
					if(technologies[j] == technology.toUpperCase()) {
						hasTechnology = true;
						break;
					}
				}
				if(!hasTechnology)
					continue;
			}

			// If the element has a brand attribute, check that it contains the current brand
			if(elements[i].attributes.getNamedItem('brand')) {
				var brands = elements[i].attributes.getNamedItem('brand').value.toLowerCase().split(',');
				var hasBrand = false;
				for(var j=0; j<brands.length; j++) {
					if(brands[j] == brand.toLowerCase()) {
						hasBrand = true;
						break;
					}
				}
				if(!hasBrand)
					continue;
			}

			// If the element has an is_secure attribute, check if we are on https
			if(elements[i].attributes.getNamedItem('is_secure')) {
				var is_https = document.location.protocol == "https:";
				var is_secure = elements[i].attributes.getNamedItem('is_secure').value.toLowerCase() == "true";
				if(is_https && !is_secure)
					continue;
				if(!is_https && is_secure)
					continue;
			}

			// Setup an empty node
			if(elements[i].childNodes.length == 0) {
				__CONFIG[elements[i].nodeName] = '';
			}
			// Read the value of the text node	
			else if(elements[i].childNodes.length == 1) {
				__CONFIG[elements[i].nodeName] = elements[i].firstChild.nodeValue;
			}
			// Parse the sub-nodes of an array node
			else {
				__CONFIG[elements[i].nodeName] = {};
				var subelements = elements[i].getElementsByTagName("*");
				for(var j=0; j<subelements.length; j++) {
					if(subelements[j].parentNode.nodeName == elements[i].nodeName) {
						if(subelements[j].childNodes.length == 0)
							__CONFIG[elements[i].nodeName][subelements[j].nodeName] = '';
						else
							__CONFIG[elements[i].nodeName][subelements[j].nodeName] = subelements[j].firstChild.nodeValue;
					}
				}
			}
		}
	}
}
addEvent(window, 'load', __setConfig);
/* END: Read the site.xml config for JavaScript */

/* Hide the find a lawyer, ask a lawyer and resource network links for Recorded Books. 
 * Also hide the divorce links.
 * Author: Chris Poirier
 * Date: October 6, 2011
 */
function hideLinksRecordedBooks() {
	// Ensure that __CONFIG is setup
	if(!__CONFIG) __setConfig();

	// Find the LawDepot menu and footer
	var LDMenu;
	if(document.getElementById('LAWDEPOT')) {
		LDMenu = getObject('LAWDEPOT').getElementsByTagName('ul')[0];
	}
	else if(document.getElementById('mm')) {
		var mm = getObject('mm');
		var lis = mm.getElementsByTagName('li');
		for(var i=0; i<lis.length; i++) {
			var li = lis[i];
			if(li.className.indexOf('LAWDEPOT') >= 0) {
				LDMenu = li.getElementsByTagName('ul')[0];
			}
		}
	}
	var footer = getObject('footer');

	// Read settings from the config array
	var showAsk = __CONFIG["showAskALawyer"].toLowerCase() == "true";
	var showFind = __CONFIG["showFindALawyer"].toLowerCase() == "true";
	var showRN = __CONFIG["showResourceNetwork"].toLowerCase() == "true";
	var showDivorce = __CONFIG["showDivorceLinks"].toLowerCase() == "true";
	
	// Don't proceed if there is nothing to hide
	if(!showAsk || !showFind || !showRN) {
		// Hide the menu links
		if(LDMenu) {
			var menuLinks = LDMenu.getElementsByTagName('a');
			for(var i=0; i<menuLinks.length; i++) {
				if(!showAsk && menuLinks[i].innerHTML.toLowerCase() == 'ask a lawyer online') {
					LDMenu.removeChild(menuLinks[i].parentNode);
					i--;
				}
				if(!showFind && menuLinks[i].innerHTML.toLowerCase() == 'find a lawyer') {
					LDMenu.removeChild(menuLinks[i].parentNode);
					i--;
				}
				if(!showRN && menuLinks[i].innerHTML.toLowerCase() == 'resource network') {
					LDMenu.removeChild(menuLinks[i].parentNode);
					i--;
				}
			}
		}
		/*
		else
			alert('No LawDepot Menu Found!');
		*/

		// Hide the footer links
		if(footer) {
			var footerLinks = footer.getElementsByTagName('a');
			for(var i=0; i<footerLinks.length; i++) {
				if(!showAsk && footerLinks[i].innerHTML.toLowerCase() == 'ask a lawyer online') {
					if(footerLinks[i].nextSibling.nodeType == 3)
						footerLinks[i].parentNode.removeChild(footerLinks[i].nextSibling);
					footerLinks[i].parentNode.removeChild(footerLinks[i]);
					i--;
				}
				if(!showFind && footerLinks[i].innerHTML.toLowerCase() == 'find a lawyer') {
					if(footerLinks[i].nextSibling.nodeType == 3)
						footerLinks[i].parentNode.removeChild(footerLinks[i].nextSibling);
					footerLinks[i].parentNode.removeChild(footerLinks[i]);
					i--;
				}
				if(!showRN && footerLinks[i].innerHTML.toLowerCase() == 'resource network') {
					if(footerLinks[i].nextSibling.nodeType == 3)
						footerLinks[i].parentNode.removeChild(footerLinks[i].nextSibling);
					footerLinks[i].parentNode.removeChild(footerLinks[i]);
					i--;
				}
			}
		}
	}

	// Find the marriage menu and left navigation
	var menuMarriage;
	if(document.getElementById('FAMILY')) {
		menuMarriage = getObject('FAMILY').getElementsByTagName('ul')[0];
	}
	else if(document.getElementById('mm')) {
		var mm = getObject('mm');
		var lis = mm.getElementsByTagName('li');
		for(var i=0; i<lis.length; i++) {
			var li = lis[i];
			if(li.className.indexOf('FAMILY') >= 0) {
				menuMarriage = li.getElementsByTagName('ul')[0];
			}
		}
	}
	var leftNav = getObject('navigation');

	if(!showDivorce) {
		// Hide the menu divorce links
		if(menuMarriage) {
			var menuLinks = menuMarriage.getElementsByTagName('a');
			for(var i=0; i<menuLinks.length; i++) {
				if(menuLinks[i].innerHTML.toLowerCase().indexOf('divorce') >= 0) {
					menuMarriage.removeChild(menuLinks[i].parentNode);
					i--;
				}
			}
		}
		
		// Hide the left nav divorce links
		if(leftNav) {
			var navLinks = leftNav.getElementsByTagName('a');
			for(var i=0; i<navLinks.length; i++) {
				var link = navLinks[i].firstChild;
				if(link && link.nodeType == 3) {
					if(link.nodeValue.toLowerCase().indexOf('divorce') >= 0) {
						navLinks[i].parentNode.removeChild(navLinks[i]);
						i--;
					}
				}
			}
		}
	}
}
addEvent(window, 'load', hideLinksRecordedBooks);
/* END: Hide the find a lawyer, ask a lawyer and resource network links for Recorded Books. */

