//constants
var FIRST_CHILD = 1;


//////////////////////
//Environment System//
//////////////////////
/*
	Manages staging / production environment variables
*/
function EnvironmentSystem() //constructor
{

}


EnvironmentSystem.prototype.productionMode = function()
{
	this.environment = 'production';

	var dom = window.document.domain.toLowerCase();

	if(dom.indexOf("totalhealthmasteryusa") >= 0)
	{
		this.shippingRatesUrl = 'http://more.totalhealthmasteryusa.com/services/shipping_rates';
	}
	else
	{
		this.shippingRatesUrl = 'http://more.thmastery.com/services/shipping_rates';
	}
}




EnvironmentSystem.prototype.stagingMode = function()
{
	this.environment = 'staging';
	this.shippingRatesUrl = 'http://more.thmastery.com/stg/services/shipping_rates';
}

var environment = new EnvironmentSystem();
environment.productionMode();
//////////////////////////
//End Environment System//
//////////////////////////



/////////////
//Utilities//
/////////////
function MyException(code, message) //constructor
{
	this.code = code;
	this.message = message;
}

/* 
	returns true if node has a given class
*/
function hasClass(node, className)
{
	if(typeof node == 'string') 
	{node = document.getElementById(node);}
	
	if(typeof node.className == 'string')
	{
		var classNames = node.className.split(' ');
			
		for(var k in classNames)
		{if(classNames[k] == className){return true;}}
	}
	
	return false;
}


function browserIsIe()
{
	return /MSIE (\d+\.\d+);/.test(navigator.userAgent) ? true : false;	
}
/////////////////
//End Utilities//
/////////////////


/////////////////
//Invoke Remote//
/////////////////

/*
	invokes subroutine designated by action on remote server, passing parameters and returning result of service as an 

object. Service must respond with json.
	url - full url of remote service
	parameters: object containing parameters to pass to url as a post field named "parameters" containing json
	throws 'service_fail' exception if the service response is not recognized
	return: an object which is the service response text after it is parsed as json
*/
function invokeRemote(url, parameters, options)
{
	if(typeof sys_trace == 'boolean' && sys_trace == true)
	{alert('invoke remote ' + JSON.encode(parameters));}

	if(browserIsIe() && options.isCrossDomain == true)
	{
	if(typeof sys_trace == 'boolean' && sys_trace == true)
	{alert('is IE');}
		if(window.XDomainRequest)
		{
		   return invokeRemoteWithXdr(url, parameters);
		}
		else
		{
			//ie without XDomainRequest is not a compatible browser
			throw new MyException('browser', 'Browser does not support XDomainRequest');
		}
	}
	else
	{

		var postData = {parameters: JSON.encode(parameters)};

		var response = jQuery.ajax({
			  url: url,
			  type: 'POST',
			  cache: false,
			  async: false,
			  dataType: 'text',
			 data: postData,
			  processData: true,
			crossDomain: true
			});

		var value = null;
		
		if(typeof sys_trace == 'boolean' && sys_trace == true)
		{alert('responseText: ' + response.responseText);}
		
		if(typeof response.responseText == 'string')
		{
			try
			{value = JSON.decode(response.responseText);}
			catch(e)
			{
				var mye = new MyException('service_fail', 
				'Unable to parse server response as json. Response: ' + response.responseText );
				mye.originalException = e;
				throw mye;
			}
		}
		else
		{
			throw new MyException('service_fail', 
				'invokeRemote: non string response from server ' + url);
		}
		
		return value;
	}
}


function invokeRemoteWithXdr(url, parameters)
{
	if(typeof sys_trace == 'boolean' && sys_trace == true)
	{alert('invoke remote with xdr ' + url + ' p ' + JSON.encode(parameters));}
	var timeoutSeconds = 8;
	var xdr = new XDomainRequest();

	if (xdr) 
	{
		xdr.onerror = function() {alert('There was an error contacting our server');};
		xdr.ontimeout = invokeRemoteWithXdr_doNothing;
		xdr.onprogress = invokeRemoteWithXdr_doNothing;
		xdr.onload = invokeRemoteWithXdr_doNothing;
		xdr.timeout = timeoutSeconds * 1000;
		xdr.open("post", url);
		var data = 'parameters=' + encodeURIComponent(JSON.encode(parameters));
		if(typeof sys_trace == 'boolean' && sys_trace == true)
		{alert('data ' + data);}

		xdr.send(data);
		var stopTime = (new Date()).getTime() + (timeoutSeconds * 1000);
		var responseObj = null;
		var success = false;
		var exception = null;
		alert("Loading shipping rates...");

		do
		{
			var response = xdr.responseText;
			//alert(response);
			//alert('loading shipping rates');

			try{
				responseObj = JSON.decode(response);
				success = true;
				//alert('xdr success true!');
			}
			catch(e)
			{exception = e;}
		}
		while((new Date()).getTime() < stopTime && success == false);
		
		
		if(typeof sys_trace == 'boolean' && sys_trace == true)
		{alert('success ' + success + ' ' +'response text: ' + xdr.responseText);}

		
		if(success == false)
		{
			var mye = new MyException('service_fail', 'Unable to parse server response as json. Response: ' + 

xdr.responseText);
			mye.originalException = exception;
			throw mye;
		}

		
		//alert('xdr.responseText: ' + xdr.responseText);
		return responseObj;
	}
	else
	{throw new MyException('browser', 'Browser does not have XDomainRequest');}
}

function invokeRemoteWithXdr_doNothing(){}

/////////////////////
//End Invoke Remote//
/////////////////////



//returns {myClass : [myElement1, ...], ... } of all named children of node
//invoke with 1 argument - getClassedNodes(node)
//node is element object
function getClassedNodes(node, classedNodes)
{
	if(arguments.length < 2)
	{classedNodes = new Object();}

	if(typeof node == 'string')
	{node = document.getElementById(node);}

	if(node.className != undefined)
	{
		var classNames = node.className.split(' ');
		
		for(var k in classNames)
		{
			if(classedNodes[classNames[k]] == undefined)
				{classedNodes[classNames[k]] = new Array();}
			classedNodes[classNames[k]].push(node);
		}
	}
	
	for(var i=0; i < node.childNodes.length; ++i)
	{getClassedNodes(node.childNodes[i], classedNodes);}
	
	return classedNodes;
}

//returns {myName : [myElement, ...], ... } of all named children of node
//invoke with 1 argument - getNamedChildren(node)
//node is string or element object
function getNamedChildren(node, namedChildren){
	if(typeof node == 'string') 
	{node = document.getElementById(node);}
	
	if(arguments.length < 2)
	{namedChildren = new Object();}
	
	for(var i=0; i < node.childNodes.length; ++i)
	{
		getNamedChildren(node.childNodes[i], namedChildren);
		
		if(typeof node.childNodes[i].name != 'undefined')
		{
			if(namedChildren[node.childNodes[i].name] == undefined)
			{namedChildren[node.childNodes[i].name] = new Array();}
			
			namedChildren[node.childNodes[i].name].push(node.childNodes[i]);
		}
	}
	
	return namedChildren;
}



/////////////////////////////
//BEGIN StaticControl Class//
/////////////////////////////

function StaticControl(node) //ctor
{
	if(arguments.length >= 1)
	{
		if(typeof node == 'string') 
		{node = document.getElementById(node);}

		this.classedNodes = getClassedNodes(node);

		for(className in this.classedNodes)
		{
			for(var i=0; i < this.classedNodes[className].length; ++i)
			{this.classedNodes[className][i].control = this;}
		}
	}
}
///////////////////////////
//END StaticControl Class//
///////////////////////////



///////////////////////////////
//BEGIN Class TemplateControl//
///////////////////////////////

//use an html template to create multiple instances of a control
//templateNodes first non text child becomes the root element of this control
//templateNode - string id of DOM element or DOM element
function TemplateControl(templateNode)
{
	this.superClass = StaticControl;

	if(arguments.length >= 1)
	{
		if(typeof templateNode == 'string')
		{templateNode = document.getElementById(templateNode);}

		var child = templateNode.firstChild;
		while(child.nodeName == '#text')
		{child = child.nextSibling;}
		
		this.rootNode = child.cloneNode(true);
		this.superClass(this.rootNode);
	}
}


/*
	optionPosition - optional. Values: FIRST_CHILD - attach this controls root as first child of node
*/
function TemplateControl_attachToNode(node, optionPosition)
{
	if(typeof node == 'string')
	{node = document.getElementById(node);}
	
	if(arguments.length > 1)
	{
		switch(optionPosition)
		{
			case FIRST_CHILD:
				if(node.hasChildNodes())
				{node.insertBefore(this.rootNode, node.firstChild);}
				else
				{node.appendChild(this.rootNode);}
				break;
		}
	}
	else
	{node.appendChild(this.rootNode);}
}
TemplateControl.prototype.attachToNode = TemplateControl_attachToNode;
/////////////////////////////
//END Class TemplateControl//
/////////////////////////////



///////////////////
////Popup Class////
///////////////////

SPopup.static = new Object();
SPopup.static.popups = new Array();
SPopup.static.topZ = 201000;
SPopup.static.baseZ = 200000;

/*
	node = HTML element's id attribute as string | reference to html node | null (null is useful for creating an invisible 

	popup that's the parent of top-level menu items)
	parent = popup's parent popup | null
	hides = true | false, can this popup close (be hidden)
*/

function SPopup(node, parent, hides) //ctor
{
	if(typeof node == 'string')
	{node = document.getElementById(node);}
	
	this.ndPopup = node;
	this.parent = parent;
	this.hides = hides;

	this.visible = !hides;
	this.children = new Array();
	this.timeoutHide = null;

	this.idNumber = SPopup.static.popups.length;
	SPopup.static.popups[this.idNumber] = this;

	if(parent != null)
		{parent.children[parent.children.length] = this;}

	if(node == null)
	{
		this.onMouseOverOriginal = null;
		this.onMouseOutOriginal = null;
	}
	else
	{
		
		if(typeof this.ndPopup.onmouseover == "function")
			{this.onMouseOverOriginal = this.ndPopup.onmouseover;}

		this.ndPopup.onmouseover = new Function("SPopup.static.popups[" + this.idNumber + "].onMouseOver();");

		if(typeof this.ndPopup.onmouseout == "function")
			{this.onMouseOutOriginal = this.ndPopup.onmouseout;}

		this.ndPopup.onmouseout = new Function("SPopup.static.popups[" + this.idNumber + "].onMouseOut();");
	}
}



//makes associated node visible; doesn't open next level of children
function SPopup_show()
{
	if(this.timeoutClose != null)
	{
		clearTimeout(this.timeoutClose);
		this.timeoutClose = null;
	}

	if(this.hides == true && this.ndPopup != null)
	{
		//jQuery(this.ndPopup).fadeIn(200);
		this.ndPopup.style.visibility = "visible";
		this.ndPopup.style.zIndex = SPopup.static.topZ;
		this.visible = true;
	}
}
SPopup.prototype.show = SPopup_show;



//shows associated node and opens next level of children
function SPopup_activate()
{
	//if we have siblings, hide siblings
	if(this.parent != null)
	{
		for(var i=0; i < this.parent.children.length; ++i)
		{
			if(this.parent.children[i] != this)
				{this.parent.children[i].hide();}
		}
	}

	this.show();
	this.keepAlive();

	//show children
	if(this.children != null)
	{
		for(var i=0; i < this.children.length; ++i)
		{
			this.children[i].show();
		}
	}
}
SPopup.prototype.activate = SPopup_activate;



//ensures this popup doesn't close
function SPopup_keepAlive()
{
	if(this.timeoutHide != null)
	{
		clearTimeout(this.timeoutHide);
		this.timeoutHide = null;
	}

	if(this.ndPopup != null)
	{this.ndPopup.style.zIndex = SPopup.static.topZ;}

	if(this.parent != null)
		this.parent.keepAlive();
}
SPopup.prototype.keepAlive = SPopup_keepAlive;



//makes element and children invisible if appropriate
function SPopup_hide()
{
	if(this.visible == false){return;}
	
	if(this.timeoutHide != null)
	{
		clearTimeout(this.timeoutHide);
		this.timeoutHide = null;
	}

	for(var i=0; i < this.children.length; ++i)
	{this.children[i].hide();}

	if(this.hides == true && this.ndPopup != null)
	{
		//jQuery(this.ndPopup).fadeOut(150);
		//jQuery(this.ndPopup).slideUp(150);
		this.ndPopup.style.visibility = 'hidden';
		this.visible = false;
	}

}
SPopup.prototype.hide = SPopup_hide;



//sets node to hide after an interval of time
function SPopup_deactivate()
{	
	if(this.timeoutHide != null)
	{clearTimeout(this.timeoutHide);}

	this.timeoutHide = setTimeout("SPopup.static.popups[" + this.idNumber + "].hide();", 600);
	
	if(this.ndPopup != null)
	{this.ndPopup.style.zIndex = SPopup.static.baseZ;}
	
	for(var i=0; i < this.children.length; ++i)
	{
		if(this.children[i].ndPopup != null)
		{this.children[i].ndPopup.style.zIndex = SPopup.static.baseZ;}
	}
}
SPopup.prototype.deactivate = SPopup_deactivate;



function SPopup_onMouseOver()
{
	if(this.onMouseOverOriginal != null)
		this.onMouseOverOriginal();

	this.activate();
}
SPopup.prototype.onMouseOver = SPopup_onMouseOver;



function SPopup_onMouseOut()
{
	if(this.onMouseOutOriginal != null)
		this.onMouseOutOriginal();

	this.deactivate();
}
SPopup.prototype.onMouseOut = SPopup_onMouseOut;

///////////////////
//End Popup Class//
///////////////////


///////////////
//HtmlLibrary//
///////////////
function HtmlLibrary() //constructor
{
	
}


/*
	removes child nodes of srcNode and attaches them as children of dstNode
 */
HtmlLibrary.prototype.moveNodeChildren = function(srcNode, dstNode)
{
	if(typeof srcNode == 'string'){srcNode = document.getElementById(srcNode);}
	if(typeof dstNode == 'string'){dstNode = document.getElementById(dstNode);}
	
	while(srcNode.hasChildNodes())
	{dstNode.appendChild(srcNode.firstChild);}
}

var htmlLibrary = new HtmlLibrary();
///////////////////
//End HtmlLibrary//
///////////////////


///////////
//JqModal//
///////////
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$(document)[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);
///////////////
//End JqModal//
///////////////

//////////////////
//JqModal Resize//
//////////////////
/*
 * jqDnR - Minimalistic Drag'n'Resize for jQuery.
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * $Version: 2007.08.19 +r2
 */

(function($){
$.fn.jqDrag=function(h){return i(this,h,'d');};
$.fn.jqResize=function(h){return i(this,h,'r');};
$.jqDnR={dnr:{},e:0,
drag:function(v){
 if(M.k == 'd')E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY});
 else E.css({width:Math.max(v.pageX-M.pX+M.W,0),height:Math.max(v.pageY-M.pY+M.H,0)});
  return false;},
stop:function(){E.css('opacity',M.o);$(document).unbind('mousemove',J.drag).unbind('mouseup',J.stop);}
};
var J=$.jqDnR,M=J.dnr,E=J.e,
i=function(e,h,k){return e.each(function(){h=(h)?$(h,e):e;
 h.bind('mousedown',{e:e,k:k},function(v){var d=v.data,p={};E=d.e;
 // attempt utilization of dimensions plugin to fix IE issues
 if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}}
 M={X:p.left||f('left')||0,Y:p.top||f('top')||0,W:f('width')||E[0].scrollWidth||0,H:f('height')||E[0].scrollHeight||0,pX:v.pageX,pY:v.pageY,k:d.k,o:E.css('opacity')};
 E.css({opacity:0.8});$(document).mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
 return false;
 });
});},
f=function(k){return parseInt(E.css(k))||false;};
})(jQuery);

//////////////////////
//End JqModal Resize//
//////////////////////




///////////////////
//DataTableReader//
///////////////////
function DataTableReader() //constructor
{
	this.fieldNames = [
		'product_description',
		'product_bullet_points',
		'product_testimonial',
		'layout_type',
		'attribute_window',
		'show_disclaimer',
		'auto_redirect_url'
	];
	
	this.fieldRes = new Array();
	
	//make regular expressions for identifying field labels
	for(var i=0; i < this.fieldNames.length; ++i)
	{this.fieldRes[i] = new RegExp("\\b(" + this.fieldNames[i] + ")\\b", "i");}
	
	this.onRe = new RegExp("\\bon\\b", "i");
	this.layoutTypeNoPriceRe = new RegExp("\\bno\\s*price\\b", "i");
	this.layoutTypeStandardRe = new RegExp("\\bstandard\\b", "i");
	this.noRe = new RegExp("\\bno\\b", "i");
}


DataTableReader.prototype.getFieldNameFromNode = function(node)
{
	var nodeText = node.innerHTML;
	for(var i=0; i < this.fieldRes.length; ++i)
	{
		var matches = nodeText.match(this.fieldRes[i]);
		if(matches != null)
		{return matches[0];}
	}
	
	return null; //no field name recognized
}


DataTableReader.prototype.getDataTableNode = function(node)
{
	if(typeof node == 'string'){node = document.getElementById(node);}
	
	if(node.nodeName == 'TABLE')
	{return node;}
	
	if(node.hasChildNodes())
	{
		for(var i=0; i < node.childNodes.length; ++i)
		{
			var result = this.getDataTableNode(node.childNodes[i]);
			if(result != null){return result;}
		}
	}
	
	return null;
}


DataTableReader.prototype.getTableRowNodes = function(tableNode)
{
	var rowsArray = new Array();
	
	if(tableNode != null)
	{
		var rowHolderNode = tableNode;
	
		//check for tbody node
		for(var i=0; i < tableNode.childNodes.length; ++i)
		{
			if(tableNode.childNodes[i].nodeName == 'TBODY')
			{
				rowHolderNode = tableNode.childNodes[i];
				break;
			}
		}
	
		for(var i=0; i < rowHolderNode.childNodes.length; ++i)
		{
			if(rowHolderNode.childNodes[i].nodeName == 'TR')
			{rowsArray[rowsArray.length] = rowHolderNode.childNodes[i];}
		}
	}
	
	return rowsArray;
}


/*
	returns {fieldName: myfieldname, value: myvalue}
	or null if no valid data found
 */
DataTableReader.prototype.getRowFieldAndValue = function(rowNode)
{
	var fieldAndValue = new Object();
	for(var i=0; i < rowNode.childNodes.length; ++i)
	{
		if(rowNode.childNodes[i].nodeName == 'TD')
		{
			var tdNode = rowNode.childNodes[i];
			var fieldName = this.getFieldNameFromNode(tdNode);
			if(fieldName == null){return null;}
			
			//find the next TD node
			do{
				if(++i > 1000){throw "Unable to find data value cell!";}
			}while(rowNode.childNodes[i].nodeName != 'TD');
			
			if(rowNode.childNodes[i].nodeName == 'TD')
			{
				fieldAndValue.fieldName = fieldName;
				fieldAndValue.value = this.getValueFromCell(fieldName, rowNode.childNodes[i]);
				return fieldAndValue;
			}
			else
			{throw "Unable to find data value cell!";}
		}
	}
}


DataTableReader.prototype.getValueFromCell = function(fieldName, cellNode)
{
	var fieldNameLower = fieldName.toLowerCase();
	
	switch(fieldNameLower)
	{
		case 'product_bullet_points':
			return cellNode;
			break;
			
		case 'product_description':
			return cellNode;
			break;
		
		case 'product_testimonial':
			return cellNode;
			break;
		
		case 'layout_type':
			return this.getLayoutTypeFromCell(cellNode);
			break;

		case 'attribute_window':
			return this.getAttributeWindowValueFromCell(cellNode);
			break;	

		case 'show_disclaimer':
			return this.getShowDisclaimerValueFromCell(cellNode);
			break;

		case 'auto_redirect_url':
			return this.getTrimmedTextFromCell(cellNode);
			break;

		default:
			throw "Unrecognized Field Name: " + fieldName + "!!";
	}
}


DataTableReader.prototype.getShowDisclaimerValueFromCell = function(cellNode)
{
	if(this.noRe.test(cellNode.innerHTML))
	{return false;}
	return true;
}


DataTableReader.prototype.getAttributeWindowValueFromCell = function(cellNode)
{
	if(this.onRe.test(cellNode.innerHTML))
	{return true;}
	
	return false;
}


DataTableReader.prototype.getLayoutTypeFromCell = function(cellNode)
{
	if(this.layoutTypeNoPriceRe.test(cellNode.innerHTML)) {return 'no_price';}
	if(this.layoutTypeStandardRe.test(cellNode.innerHTML)) {return 'standard';}

	return null;
}


DataTableReader.prototype.getTrimmedTextFromCell = function(cellNode)
{
	var str = cellNode.innerHTML;
	//trim white space
	str = str.replace('&nbsp;', '');
	return str.replace(/^\s+|\s+$/g, '') ; 
}


DataTableReader.prototype.getData = function(tableNode)
{
	var data = new Object();

	if(tableNode != null)
	{
		var rowNodes = this.getTableRowNodes(tableNode);
	
		for(var i=0; i < rowNodes.length; ++i)
		{
			var fieldAndValue = this.getRowFieldAndValue(rowNodes[i]);
			if(fieldAndValue != null)
			{
				data[fieldAndValue.fieldName] = fieldAndValue.value;
			}
		}
	}

	return data;
}
////////////////////////
//End DataTableReader//
////////////////////////



/////////////////////////
//Secret Table Processor//
/////////////////////////

function SecretTableProcessor() //constructor
{
}


SecretTableProcessor.prototype.process = function()
{
	var secretTable = document.getElementById('secret_table');
	
	if(secretTable != null)
	{
		var dataTableReader = new DataTableReader();
		data = dataTableReader.getData(secretTable);
		
		//process an auto redirect url
		if(data.auto_redirect_url != undefined)
		{
			window.location = data.auto_redirect_url;
		}
	}
}

/////////////////////////////
//End Secret Table Processor//
/////////////////////////////

////////////////////////////////
//Members Code//
////////////////////////////////

var MembersLibrary = new Object() //constructor
MembersLibrary.memberLevels = ['silver', 'gold', 'platinum'];


MembersLibrary.gotoMemberLevelHomeIfNeeded = function()
{
	var ml = window.MembersLibrary;
	var subsData = document.getElementById('subscriptions_data_node');
	subsData = subsData.innerHTML.toLowerCase();

	for(var i = ml.memberLevels.length - 1; i >= 0; --i)
	{
		if(subsData.indexOf(ml.memberLevels[i]) >= 0)
		{
			if(!(window.location.href.indexOf(ml.memberLevels[i]) >= 0))
			{
				window.location.assign('http://thmastery.com/members/' + ml.memberLevels[i]);
			}
			break;
		}
	}
}



MembersLibrary.showMemberSubscriptions = function()
{
	var ml = window.MembersLibrary;
	var displayString = '';
	var subsData = document.getElementById('subscriptions_data_node');

	subsData = subsData.innerHTML.toLowerCase();
	var wrote = false;
	
	for(var i=0; i < ml.memberLevels.length; ++i)
	{
	
		if(subsData.indexOf(ml.memberLevels[i]) >= 0)
		{
			if(wrote){displayString += ' ';}else{wrote = true;}
			displayString += ml.memberLevels[i];
		}
	}
	
	if(displayString == '')
	{displayString = 'None';}
	
	document.getElementById('subscriptions_display_node').innerHTML = displayString;
}
////////////////////////////////////////
//End Members Code//
///////////////////////////////////////
