(function(){

	// Map over jQuery in case of overwrite
	if ( typeof MENTOR != "undefined" ){
		var _MENTOR = MENTOR;
	}

	var MENTOR = window.MENTOR = function() {
		// If the context is a namespace object, return a new object
		return this instanceof MENTOR ? this.init() : new MENTOR();
	};

	MENTOR.prototype = {
	
	}


	jQuery.extend(MENTOR,{
	
		//function that runs if call MENTOR()
		init: function(){},


		dataStore: [],
/* ********* MENTORAJAX METHOD  **************** */


		mentorajax: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){								//if the function needs to be executes on dom ready
				jQuery(document).ready(function(){MENTOR.mentorajaxprocess(options)}) //enclose it in a jquery function
			}else{															
				MENTOR.mentorajaxprocess(options)							//otherwise execute it right away
			}
	
		},

		//ajax function
		mentorajaxprocess: function(newoptions){
			var prop = {													//the default properties
				url: 'ajax.html',											//the url which will be loaded in the ajax call
				triggerClass: 'trigger',									//the class on the links which will cause the ajax call
				targetTag: 'div',											//the tag of the elements you want to fill with the ajax call
				targetClass: 'target',										//the class of the elements you want to fill with the ajax call
				activeParentTag: 'tr',										//the tag of the parent element you want to attach a class to when the trigger has been clicked
				activeClass: 'expanded',									//the class you want to attach to the parent element 
				passQstring: 'no',											//grab the querystring from the triggers href to pass with the ajax
				loadingImage: '/common/images/offers/ajax-loader.gif',		//path to the loading image
				errorFunction: function(){
					if (window.console && window.console.error) {			//throws the error message to the console when there is a console
	    			    console.error(arguments);
	    			}
				},
				customSuccess: function(datapass, objectpass){
					if(window.console){
						console.log("success")
					}
				},
				mode: 'simpleFill',											//the mode, options are simpleFill, modal, showHide
				modalWidth: 500,											//width of the modal window
				modalHeight: 500,											//height of the modal window
				dependenciesPath: '/common/includes/',						//the path to where dependendcies are located
				modalCss: 'styled',											//whether the position of modal window should be set with external css or "computed"
				activateFirst: 'yes',										//if set to yes the first link is selected onload in single target mode
				modalAppend: 'body'											//selector for where the modal window should be appended
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
		
			switch(options.mode){											
			case "simpleFill":												//if is in simpleFill mode

				jQuery("a."+options.triggerClass).each(function(){				//for each of the trigger links
					var $this=jQuery(this)										//save a reference to the current trigger
					jQuery(this).click(function(){								//when current link is clicked on 					

						jQuery(this).parents(options.activeParentTag+":first").addClass(options.activeClass);	//add the active class to the activeparenttag
	
						if(options.passQstring=='yes'){						//if the querystring needs to be passed
							var mentorPassedUrl = options.url;
							options.url = mentorPassedUrl.split('?')[0] + '?' + jQuery(this).attr("href").split('?')[1];	//grab the querystring from the href
						}

						if($this.next(options.targetTag + "."+options.targetClass).is(":empty")){	//if the target is empty							
							var $loadingDiv = jQuery('<div><img src="' + options.loadingImage + '"></div>');	//create the loading div
							$this.next(options.targetTag + "."+options.targetClass).append($loadingDiv);	//add the loading div to the target				
							jQuery.ajax({																
								url: options.url,							//set the url for the ajax call
								type: "GET",								//type of ajax call
								dataType: "html",							//the type of data to be returned by the ajax call
								error: options.errorFunction,				//the function to call when there is an error with the ajax
								success: function(data){
									$this.next(options.targetTag + "."+options.targetClass).html(data);		//fill the target with the returned html
									options.customSuccess(data,$this);
								}
							});			
						}

						return false;										//cancel the default function of the link
					});

				});
				break
			
			case "singleTarget":												//if is in singleTarget mode

				jQuery("a."+options.triggerClass).each(function(){				//for each of the trigger links
					var $this=jQuery(this)										//save a reference to the current trigger
					jQuery(this).click(function(){								//when current link is clicked on 					

						jQuery("a."+options.triggerClass).each(function(){
							jQuery(this).parents(options.activeParentTag+":first").removeClass(options.activeClass);	//remove the active class from all the activeparenttag
						})
						jQuery(this).parents(options.activeParentTag+":first").addClass(options.activeClass);	//add the active class to the activeparenttag
	
						if(options.passQstring=='yes'){						//if the querystring needs to be passed
							var mentorPassedUrl = options.url;
							options.url = mentorPassedUrl.split('?')[0] + '?' + jQuery(this).attr("href").split('?')[1];	//grab the querystring from the href
						}

						var $loadingDiv = jQuery('<div><img src="' + options.loadingImage + '"></div>');	//create the loading div
						jQuery(options.targetTag + "."+options.targetClass).empty().append($loadingDiv);	//add the loading div to the target				
						jQuery.ajax({																
							url: options.url,							//set the url for the ajax call
							type: "GET",								//type of ajax call
							dataType: "html",							//the type of data to be returned by the ajax call
							error: options.errorFunction,				//the function to call when there is an error with the ajax
							success: function(data){
								jQuery(options.targetTag + "."+options.targetClass).html(data);		//fill the target with the returned html
								options.customSuccess(data,jQuery(options.targetTag + "."+options.targetClass));
							}
						});			
						return false;										//cancel the default function of the link
					});

				});
				if(options.activateFirst='yes'){
					jQuery("a."+options.triggerClass+":first").trigger("click");
				}
				break
			
			case "modal":													//if the mode is modal
			
				jQuery("a."+options.triggerClass).click(function(){					//bind a click to all the trigger links
					jQuery("#mb_center").empty().remove();									//remove any previously created windows
					$mbCenter = jQuery('<div id="mb_center"></div>')					//create a reference to the new window
					jQuery('<div id="mb_contents"></div>')							//create the content div inside
					.append('<div id="mb_copy"></div>')							//append copy div to content div
					.appendTo($mbCenter);										//append it all to modal window div
					jQuery("#mb_copy",$mbCenter)
					.append('<div id="mb_header"><a href="#" title="Close Window" id="mb_close_link">Close This Window</a></div>')	//append close link
					if(options.modalCss==='computed'){								//use this option if the position of the window should be computed and added inline
						var offsetTOP = {}											//create offsetTop object 
						jQuery(this).offset({},offsetTOP)								//find the position of the link clicked on the page
						var toppos = offsetTOP.top-(options.modalHeight/2);			//top position should be the top position of the link minus half the height of the modal window
						if(toppos<0){toppos=0}										//if the top position would cause the window to be off the page, set the position to 0
						var leftpos = (jQuery(window).width()/2)-(options.modalWidth/2)	//left position of window is half the width of page minus half of the modal window
						if(leftpos<0){leftpos=0}									//if the left position is negative, make it 0
						$mbCenter
						.css({
							height:options.modalHeight,								//set the height of the modal window
							width:options.modalWidth,								//set the width of the modal window
							left: leftpos,											//set the left position
							top: toppos,											//set the top position
							position: 'absolute'									//make the window div have absolute positioning
						})
					}	
					$mbCenter.appendTo(options.modalAppend);											//append the window to the body
					if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
						jQuery("select").css({'visibility':'hidden'});
					}
					var $loadingDiv = jQuery('<div class="modalloading"><img src="' + options.loadingImage + '"></div>').appendTo("#mb_copy");	//append the loading image to the modal window				
					
					if(options.modalCss==='computed'){
						jQuery(window).resize(function(){								//repostion the modal window on browser resize
							var leftpos = (jQuery(window).width()/2)-(options.modalWidth/2)	//left position of window is half the width of page minus half the width of the modal window
							jQuery("#mb_center")
							.css({
								left: leftpos
							})
						});
					}
					jQuery("#mb_close_link").click(function(){						//bind a click event to the close button
						jQuery("*",jQuery("#mb_center")).unbind();
						jQuery("#mb_center").empty().remove();								//remove modal window on close
						if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
							jQuery("select").css({'visibility':'visible'});
						}
						return false;
					});
					if(options.passQstring=='yes'){						//if the querystring needs to be passed
						var mentorPassedUrl = options.url;
						options.url = mentorPassedUrl.split('?')[0] + '?' + jQuery(this).attr("href").split('?')[1];	//grab the querystring from the href
					}
					jQuery.ajax({																
						url: options.url,										//get the url
						type: "GET",
						dataType: "html",
						error: options.errorFunction,
						success: function(data){
							jQuery("#mb_copy").find("div:has(img)").remove().end().append(data);							//insert the retrieved html into the modal window
							options.customSuccess(data,jQuery("#mb_copy"));
						}
					});			
					return false;												//prevent the default behavior of the link click
				});
				break

			case "showHide":
		
				jQuery(options.targetTag + "." + options.targetClass).hide();		//hide the targets
				jQuery("a."+options.triggerClass).each(function(){					//for each trigger link
					var $this=jQuery(this)											//save a reference to the current link
					jQuery(this).toggle(function(){									//bind a toggle to the current link					
						jQuery(this).parents(options.activeParentTag+":first").addClass(options.activeClass);	//add the active class to the active parent tag 
		
						if(options.passQstring=='yes'){						//if the querystring needs to be passed
							var mentorPassedUrl = options.url;
							options.url = mentorPassedUrl.split('?')[0] + '?' + jQuery(this).attr("href").split('?')[1];	//grab the querystring from the href
						}
						jQuery(this).next("."+options.targetClass).animate({			//animate the target div going from zero height to its full height				
							height: 'toggle', opacity: 'toggle'
						}, 185,function(){														
							if($this.next(options.targetTag + "."+options.targetClass).is(":empty")){	//if the target is empty							
								var $loadingDiv = jQuery('<div><img src="' + options.loadingImage + '"></div>');	//create the loading div
								$this.next(options.targetTag + "."+options.targetClass).append($loadingDiv);//append the loading div to the target
								jQuery.ajax({																
									url: options.url,
									type: "GET",
									dataType: "html",
									error: options.errorFunction,
									success: function(data){
										$this.next(options.targetTag + "." + options.targetClass).html(data); 	//fill the target with the retrieved html
										options.customSuccess(data,$this);
									}
								});			
							}
						});
						return false;	//prevent the default behaviour of the click
					},function(){  //on the second click
						jQuery(this).parents(options.activeParentTag+":first").removeClass(options.activeClass);	//remove the active class
						jQuery(this).next(options.targetTag + "." + options.targetClass).animate({				//toggle the height of the target back to zero
							height: 'toggle', opacity: 'toggle'
						}, 185);
						return false;  //prevent the default behaviour of the click
					});
				});
				break
			}
	
		},

/* ********* VALIDATE NEW METHOD  **************** */


		validatenew: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){
				jQuery(document).ready(function(){MENTOR.validatenewprocess(options)})
			}else{
				MENTOR.validatenewprocess(options)
			}
	
		},
		validatenewprocess: function(newoptions){
			var prop = {
				formId: 'validationForm',
				errorTag: 'p',
				errorClass: 'error',
				bigAlertClass: 'error',
				limitClass: 'limitvalidate',
				requiredClass: 'mgcrequired',
				language:'english'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions)
			jQuery.getJSON("/js/languages/"+options.language+".js",function(data,textStatus){
				MENTOR.languagecache=data.language;
			})
			jQuery(options.errorTag + '.' + options.errorClass,jQuery('#' + options.formId)).remove();	//remove any the error messages
			jQuery("input."+options.requiredClass+", textarea."+options.requiredClass+", select."+options.requiredClass,jQuery('#' + options.formId)).bind("blur.mgcvalidation",function(){ //bind a blur listener to all form fields
				MENTOR.checkfieldnew(options,jQuery(this));
			});
			jQuery('#' + options.formId).submit(function(){													//bind a submit event to the form
				MENTOR.dataStore=[];
				var $submitdiv = jQuery(this).find("div.submit");
				var $submitcache = $submitdiv.html();
				$submitdiv.html('<div class="callout message"><img src="/images/anim-loading.gif" class="align-left" /> Validating</div>')
				jQuery('#error,#bigAlertUl').remove();																	//remove any previously created submit error message
				jQuery(options.errorTag + '.'+ options.errorClass,jQuery('#' + options.formId)).remove();	//remove any previously created error message
				jQuery('div.error',jQuery('#' + options.formId)).removeClass("error");
				jQuery("."+options.requiredClass,jQuery('#' + options.formId)).each(function(){
					MENTOR.checkfieldnew(options,jQuery(this));
				});
				jQuery("."+options.limitClass,jQuery('#' + options.formId)).each(function(){
					var eleme = jQuery(this)
					if(parseInt(jQuery.trim(eleme.val()).length,10)>0){
						MENTOR.checkfieldnew(options,eleme);
					}
				})

				var numWarnings=MENTOR.dataStore.length;
				if (numWarnings>0){																		//if there are errors
					var $bigAlert = jQuery('<div></div>').attr({'id': 'error', 'class': options.bigAlertClass})							//create the div that will show any errors on submit
					var alertmessage=MENTOR.languagecache["Please correct errors with following"].replace('||insertnumber||',numWarnings)
					$bigAlert.append('<span><strong>'+alertmessage+'</strong></span>')	//append the first line of the submit error message
					jQuery('<div class="clear">').insertAfter($bigAlert)
					$bigAlert.insertBefore('#' + options.formId);												//insert the error message before the form
					$bigAlert.prepend('<a name="erroranchor"></a>')
					jQuery('<div class="clear">').insertAfter($bigAlert)
					var $bigAlertUl = jQuery('<ul id="bigAlertUl" class="error-list"></ul>')
					jQuery.each(MENTOR.dataStore,function(i,n){
						$bigAlertUl.append('<li>'+n+'</li>')
					})
					$bigAlertUl.insertBefore('#' + options.formId);
					$submitdiv.html($submitcache)
					window.location="#erroranchor";
					return false;																		//stop the submit from happening
				};
				$submitdiv.html('<div class="callout message"><img src="/images/anim-loading.gif" class="align-left" /> Submitting</div>')
				jQuery(".removeonsubmit",jQuery('#' + options.formId)).remove();
			});
		},
		checkfieldnew: function(newoptions,eleme){
			var prop = {
				errorTag: 'p',
				emailClass: 'email',
				phoneClass: 'phone',
				numericClass: 'numeric'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions)
			eleme.next(options.errorTag).remove();																//remove any previously created error messages
			var $closediv = eleme.closest("div")
			$closediv.removeClass("error")
			if(eleme.is(".mgcradioset")){																	//if the required element is a radio button
				var curfield=eleme.find("label:first").text();

				var errorMessage;
				if(typeof MENTOR.languagecache["error"+eleme.attr("name")]==='undefined'){
					errorMessage = curfield + ' ' + MENTOR.languagecache["is a required field"];								//create a variable of the error message
				}else{
					errorMessage = MENTOR.languagecache["error"+eleme.attr("name")];								//create a variable of the error message
				}
				var radiocheckedcount=0																//create a counter set to 0
				jQuery(":radio",eleme).each(function(){											//for each radio button in the same listitem 	
					if(jQuery(this).is(":checked")){																//if the radio is checked
						radiocheckedcount++														//add 1 to the counter (should really never reach more than 1 with radio buttons)
					}
				})
				if(radiocheckedcount==0){															//if the counter is still at 0 then no radio buttons were checked
					options.errorMessage = errorMessage				
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield)
				}
			}
			if(eleme.is(".mgccheckset")){																	//if the required element is a checkbox
				var curfield=eleme.find("label:first").text();
				var errorMessage;
				if(typeof MENTOR.languagecache["error"+eleme.attr("name")]==='undefined'){
					errorMessage = curfield + ' ' + MENTOR.languagecache["is a required field"];								//create a variable of the error message
				}else{
					errorMessage = MENTOR.languagecache["error"+eleme.attr("name")];								//create a variable of the error message
				}
				var checkboxcheckedcount=0																//create a counter set to 0
				jQuery(":checkbox",eleme).each(function(){											//for each checkbox in the same list item 	
					if(jQuery(this).is(":checked")){																//if the radio is checked
						checkboxcheckedcount++														//add 1 to the counter (should really never reach more than 1 with radio buttons)
					}
				})
				//return false;
				
				if(checkboxcheckedcount==0){															//if the counter is still at 0 then no checkboxes were checked
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield)
				}
				if(jQuery(".createdcheckother",eleme).attr("checked")==true){
					if(jQuery(".checkboxother",eleme).val()==''){
						var errorMessage;
						if(typeof MENTOR.languagecache["error"+eleme.attr("name")+"other"]==='undefined'){
							errorMessage = curfield + ' Other is a required field';								//create a variable of the error message
						}else{
							errorMessage = MENTOR.languagecache["error"+eleme.attr("name")+"other"];								//create a variable of the error message
						}
						options.errorMessage = errorMessage
						MENTOR.insertErrorMessagenew(options,eleme,$closediv)
						MENTOR.dataStore.push(curfield)
					}
				}
			}

			if (eleme.attr("mgc:action")=="otherOption"){											//if this is a select field with an other afterward
				if(jQuery.trim(jQuery("option:selected",eleme).val())=='Other (please specify):') {							//if the other item is selected
					var $othertext = eleme.parents(":first").find("span.showingoption").find("input")					//set a variable to hold the jquery object of the other text field
					if($othertext.val()==''){														//if the other text field is empty
						$othertext.next('p').remove();											//remove any previously created error messages
						var curfield = jQuery("label[for="+eleme.attr("id")+"]");	//get the label of the current field
						if(curfield.length>0){
							var errorMessage
							if(typeof MENTOR.languagecache["error"+eleme.attr("name")+"other"]==='undefined'){
								errorMessage = curfield.text() + ' Other is a required field';					//create a variable of the error message
							}else{
								errorMessage = MENTOR.languagecache["error"+eleme.attr("name")+"other"];					//create a variable of the error message
							}
							options.errorMessage = errorMessage
						}
						MENTOR.insertErrorMessagenew(options,$othertext,$closediv)
						MENTOR.dataStore.push(curfield.text() + ' Other')
					}else{																			//if the field is not blank
						$othertext.next('p').remove();											//remove error messages
					}
				}
			}
			if((eleme.is(":text") || eleme.is("textarea") || eleme.is("select") || eleme.is(":password") || eleme.is(":file"))&&((jQuery.trim(eleme.val()) == '')||(eleme.val() == null))&&((!eleme.is(".mgccanbeempty"))||(eleme.val() == null))){																	//if the required input is empty

				var curfield=jQuery("label[for="+eleme.attr("id")+"]");
				if(curfield.length>0){
					var errorMessage;
					if(typeof MENTOR.languagecache["error"+eleme.attr("name")]==='undefined'){
						errorMessage = curfield.text() + ' ' + MENTOR.languagecache["is a required field"];								//create a variable of the error message
					}else{
						errorMessage = MENTOR.languagecache["error"+eleme.attr("name")];								//create a variable of the error message
					}
					options.errorMessage = errorMessage
				}
				
				MENTOR.insertErrorMessagenew(options,eleme,$closediv)
				MENTOR.dataStore.push(curfield.text())

			}
			if(eleme.is('.' + options.emailClass)){																//if this is the email field
				if(eleme[0].value != '' && !/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(eleme[0].value)){			//if the field is not empty and fails the regular expression test

					var errorMessage = MENTOR.languagecache["proper email format"];	//create the error messsage
					
					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())

				}
			}
			if(eleme.is('.validatemacaddress')){																//if this is the email field
				if(eleme[0].value != '' && !/^([0-9a-fA-F][0-9a-fA-F]-?){5}([0-9a-fA-F][0-9a-fA-F])$/.test(eleme[0].value)){			//if the field is not empty and fails the regular expression test

					var errorMessage = "Please enter the MAC address in the following format: xx-xx-xx-xx-xx-xx";	//create the error messsage

					var curfield=jQuery("label[for="+eleme.attr("id")+"]");

					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())

				}
			}
			if(eleme.is('.mgc_passwordfirst')){																//if this field is the first of two password fields that need to be the same
				if(eleme.val()!==jQuery(".mgc_passwordsecond",eleme.parents("form:first")).val()){
					var errorMessage = 'Please make sure the two password fields match';	//create the error messsage
					
					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())
				}
			}
			if(eleme.is('.mgc_invalidvalue')){																//if this field has been invalidated elsewhere

					var errorMessage = 'Please use a valid value';	//create the error messsage
					
					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())

			}
			if(eleme.is('#tlausername')){																//if this is the tla username field
				if(eleme[0].value != '' && !/\w{6,}/.test(eleme[0].value)){			//if the field is not empty and fails the regular expression test

					var errorMessage = 'Please use proper username format (at least 6 alphanumeric characters)';	//create the error messsage
					
					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())

				}
			}
			if(eleme.is('#tlapassword')){																//if this is the tla username field
				var  tlaprob=false;
				if((jQuery("#tlausername")[0].value == '' || jQuery("#tlapassword")[0].value == '') && (jQuery("#tlausername").val() != '' || jQuery("#tlapassword").val() != '')&&(!tlaprob)){

					var errorMessage = 'Please fill out both the username and password';	//create the error messsage
					tlaprob=true;

					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())
				}
				if((jQuery("#tlapassword")[0].value != '' && jQuery("#tlapassword")[0].value.length < 6)&&(!tlaprob)){
					var errorMessage = 'Please use proper password format (at least 6 characters)';	//create the error messsage
					tlaprob=true;

					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())
				}
				if((jQuery("#tlapassword")[0].value !== '' || jQuery("#pswd2")[0].value !== '') && (jQuery("#tlapassword")[0].value !== jQuery("#pswd2")[0].value)&&(!tlaprob)){
					var errorMessage = 'Please make sure your password and your verified password match';	//create the error messsage
					tlaprob=true;

					var curfield=jQuery("label[for="+eleme.attr("id")+"]");
					
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())
				}
			}

			if(eleme.is('.' + options.limitClass)){																//if this is the phone field
				var limit=eleme.attr("rel")
				if(limit!=''&&!isNaN(limit)){
					limit=parseInt(limit,10);
					var ellength=parseInt((eleme.val()).length,10)
					if(ellength>limit){
						var errorMessage = 'Too many characters, please limit your input to ' + limit + ' characters. You entered ' + ellength + ' characters.';							//create the error messsage
				
						var curfield=jQuery("label[for="+eleme.attr("id")+"]");
						options.errorMessage = errorMessage
						MENTOR.insertErrorMessagenew(options,eleme,$closediv)
						MENTOR.dataStore.push(curfield.text())

					}
				}
			}

			if(eleme.is('.' + options.numericClass)){																//if this is a field which should only be numeric (is marked by the class numeric)
				var curfield=jQuery("label[for="+eleme.attr("id")+"]");
				if(eleme[0].value != '' && isNaN(eleme[0].value)){											//if the field is not empty and it is not a number
					var errorMessage = 'Please enter a numeric value ' + curfield.text();						//create the error messsage
				
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessagenew(options,eleme,$closediv)
					MENTOR.dataStore.push(curfield.text())

				}
			}
			if(eleme.is('.mgcemailcheck')){																//if this is a field which should only be numeric (is marked by the class numeric)
				var curfield=jQuery("label[for="+eleme.attr("id")+"]");
				jQuery.ajax({
					type:"POST",
					port: "emailcheck",
					mode: "abort",
					async: false,
					url:"/screener/screen_email.cfm",
					data:{'email':eleme.val()},
					success: function(data){
						if(jQuery.trim(data)==='false'){
							var errorMessage = 'We do not grant access to personal, non-business email accounts. Please use your business email address.';						//create the error messsage
				
							options.errorMessage = errorMessage
							var $container = eleme.closest("div")
							var $errexist = jQuery("."+options.errorClass,$container)
							if($errexist.length>0){
								$errexist.remove();
							}
							MENTOR.insertErrorMessagenew(options,eleme,$closediv)
							MENTOR.dataStore.push(curfield.text())
						}
					}
				})
			}
		},
		insertErrorMessagenew: function(newoptions,$insertAfterPoint,$closediv){
			var prop = {
				errorTag: 'p',
				errorMessage: 'There is an error with this field.'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions)
			$closediv.addClass("error")

			var $errmess = jQuery('<' + options.errorTag + '></' + options.errorTag + '>')								//create the paragraph that will hold the rror message
			.text(options.errorMessage)																//put the error message in the paragraph
			.addClass(options.errorClass)																//add the error class to the paragraph
			
			$errmess.insertAfter($insertAfterPoint);															//insert the paragraph after the email field
		},

/* ********* VALIDATE METHOD  **************** */


		validate: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){
				jQuery(document).ready(function(){MENTOR.validateprocess(options)})
			}else{
				MENTOR.validateprocess(options)
			}
	
		},
		validateprocess: function(newoptions){
			var prop = {
				errorTag: 'p',
				formId: 'validationForm',
				tagToUse: 'tr',
				labelOutsideDiv: false,
				bigAlertClass: 'error',
				limitClass: 'limitvalidate',
				errorClass: 'error',
				labelRelationship: '+ div >'				//the relationship between the label and input being checked in terms of css selecltor, other one is '+'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions)

						
				jQuery(options.tagToUse,jQuery('#' + options.formId)).not(options.tagToUse+".serverside").removeClass('error');											//reset the page by removing the error class from lis
				jQuery(options.errorTag + '.' + options.errorClass,jQuery('#' + options.formId)).not(options.tagToUse+".serverside " + options.errorTag + "." + options.errorClass).remove();											//and remove the spans that hold the error messages

				var $blurFormItem;																			//create the variable that will hold the jquery object of the last item blurred
	
				function createblurformitem(){																// a function to bind the blur listener to all form fields
					jQuery("input, textarea, select",jQuery('#' + options.formId)).unbind("blur",function(){					//make sure any previously binds of this function are removed so no double firing
						$blurFormItem=jQuery(this);																//the function which would have been previously bound
					});
					jQuery("input, textarea, select",jQuery('#' + options.formId)).bind("blur",function(){						//bind a blur listener to all form fields
						$blurFormItem=jQuery(this);															//whenever an item is blurred, save the jquery object to the variable to be referenced
					});
				}

				createblurformitem();																		//call just created a function, was created as a function so can be called as an ajax callback when new fields are added to a page
	
				jQuery("input, select, textarea",jQuery('#' + options.formId)).not(":submit").not(":image").focus(function(){				//bind a focus listener to all form fields except the submit button
					var $focusListItem = jQuery(this).parents(options.tagToUse+':first');										//create a variable of the jquery object of the parent list item
					var $blurItem = $blurFormItem;															//reference blurItem to the previously saved jquery object of the last blurred element
					if ($blurItem != undefined){															//if blurItem is defined
						if (!$blurItem.is("body")){															//and it isnt the body element	
							if($blurItem.parents().index($focusListItem[0])==-1){							//if the blurred item does not share the same parent list item as the focused item
								var $context = $blurItem.parents(options.tagToUse+':first')
								jQuery("label.required "+options.labelRelationship+" input:text,label.required "+options.labelRelationship+" input:password, label.required "+options.labelRelationship+" select, label.required "+options.labelRelationship+" textarea",$context).each(function(){	//iterate through all the fields that share a parent listitem with the blurred element
									MENTOR.checkfield(options,jQuery(this));													//run validation on each of the fields
							
								});
								jQuery(options.tagToUse+":has(label.required)",$context).find(":has(input:checkbox)").each(function(){
									var eleme = jQuery(this).find("input:checkbox:first")
									MENTOR.checkfield(options,eleme);
								})
								jQuery(options.tagToUse+":has(label.required)",$context).find(":has(input:radio)").each(function(){
									var eleme = jQuery(this).find("input:radio:first")
									MENTOR.checkfield(options,eleme);
								})
								jQuery("."+options.limitClass,$context).each(function(){
									var eleme = jQuery(this)
									if(parseInt(jQuery.trim(eleme.val()).length,10)>0){
										MENTOR.checkfield(options,eleme);
									}
								})
							}
						}
					}
				});

				jQuery('#' + options.formId).submit(function(){													//bind a submit event to the form
					jQuery('#error,#bigAlertUl').remove();																	//remove any previously created submit error message
					jQuery(options.errorTag + '.'+ options.errorClass,jQuery('#' + options.formId)).remove();																	//remove any previously created error message
					jQuery('div.error',jQuery('#' + options.formId)).removeClass("error");
					jQuery(options.tagToUse+'.error',jQuery('#' + options.formId)).removeClass("error");														//remove any previously created error class
					jQuery("label.required "+options.labelRelationship+" input:password,label.required "+options.labelRelationship+" input:text, label.required "+options.labelRelationship+" select, label.required "+options.labelRelationship+" textarea",jQuery('#' + options.formId)).each(function(){
						MENTOR.checkfield(options,jQuery(this));
					});
					jQuery(options.tagToUse+":has(label.required)",jQuery('#' + options.formId)).find(":has(input:checkbox)").each(function(){
						var eleme = jQuery(this).find("input:checkbox:first")
						MENTOR.checkfield(options,eleme);
					})
					jQuery(options.tagToUse+":has(label.required)",jQuery('#' + options.formId)).find(":has(input:radio)").each(function(){
						var eleme = jQuery(this).find("input:radio:first")
						MENTOR.checkfield(options,eleme);
					})
					jQuery("."+options.limitClass,jQuery('#' + options.formId)).each(function(){
						var eleme = jQuery(this)
						if(parseInt(jQuery.trim(eleme.val()).length,10)>0){
							MENTOR.checkfield(options,eleme);
						}
					})

					var numWarnings;
					numWarnings = jQuery(options.errorTag + '.'+ options.errorClass,jQuery('#' + options.formId)).length;
					if (numWarnings){																		//if there are errors
						var fieldList = [];																	//create an array 
						jQuery(options.errorTag + '.'+ options.errorClass,jQuery('#' + options.formId)).each(function(){							//iterate through all the errors
							if(options.labelOutsideDiv){
								if(jQuery(this).prev().is(":text")||jQuery(this).prev().is(":password")||jQuery(this).prev().is("select")||jQuery(this).prev().is("textarea")){
									var fieldmess = jQuery(this).parents("div:first").prev().text()
									if(fieldmess!==''){
										fieldList.push(fieldmess);
									}
								}
							}else{
								fieldList.push(jQuery(this).prev().prev().text());									//add the text from each label of fields that have an error to the array
							}

						});
						jQuery(options.tagToUse+'.error',jQuery('#' + options.formId)).each(function(){											//iterate through all the radio button errors
							jQuery(":radio:first",jQuery(this)).each(function(){
								if(options.labelOutsideDiv){
									var fieldmess = jQuery(this).parents(options.tagToUse+".error").find("label.required:first").text()
									if(fieldmess!==''){
										fieldList.push(fieldmess);
									}
								}else{
									fieldList.push(jQuery(this).parents(options.tagToUse+".error").children("label.required").text());
								}
							})
						});
						jQuery(options.tagToUse+'.error',jQuery('#' + options.formId)).each(function(){										//iterate through all the checkbox errors
							jQuery(":checkbox:first",jQuery(this)).each(function(){
								if(options.labelOutsideDiv){
									var fieldmess = jQuery(this).parents(options.tagToUse+".error").find("label.required:first").text()
									if(fieldmess!==''&&(jQuery(":checked",jQuery(this).parents(options.tagToUse+".error")).length==0)){
										fieldList.push(fieldmess);
									}
								}else{
									fieldList.push(jQuery(this).parents(options.tagToUse+".error").children("label.required").text());
								}
							})
						});
						var $bigAlert = jQuery('<div></div>').attr({'id': 'error', 'class': options.bigAlertClass})							//create the div that will show any errors on submit
						
						if(options.labelOutsideDiv){
							$bigAlert.append('<span><strong>Please correct errors with following ' + numWarnings + ' fields:</strong></span>')	//append the first line of the submit error message
							jQuery('<div class="clear">').insertAfter($bigAlert)
							.append('' + fieldList.join(',  '))													//append the list of fields that have an error
							$bigAlert.insertBefore('#' + options.formId);												//insert the error message before the form
							$bigAlert.prepend('<a name="erroranchor"></a>')
							jQuery('<div class="clear">').insertAfter($bigAlert)
							var $bigAlertUl = jQuery('<ul id="bigAlertUl" class="error-list"></ul>')
							jQuery.each(fieldList,function(i,n){
								$bigAlertUl.append('<li>'+n+'</li>')
							})
							$bigAlertUl.insertBefore('#' + options.formId);
						}else{						
							$bigAlert.append('Please correct errors with following ' + numWarnings + ' fields: <br />')	//append the first line of the submit error message
							.append('' + fieldList.join(',  '))													//append the list of fields that have an error
							.prepend('<a name="erroranchor"></a>')
							.insertBefore('#' + options.formId);												//insert the error message before the form
						}
						window.location="#erroranchor";
						return false;																		//stop the submit from happening
					};
					jQuery(".removeonsubmit",jQuery('#' + options.formId)).remove();
				});

		},
		checkfield: function(newoptions,eleme){
			var prop = {
				errorTag: 'p',
				emailClass: 'email',
				phoneClass: 'phone',
				numericClass: 'numeric'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions)
			eleme.next(options.errorTag).remove();																//remove any previously created error messages
			eleme.parents("div:first").removeClass("error")
			var $listItem = eleme.parents(options.tagToUse+':first');												//create a variable to reuse of the jquery object that is the parent list item of the input
			$listItem.removeClass('error');											//remove error class from list item	
			if(eleme.is(":radio")){																	//if the required element is a radio button
				$listItem.find(options.errorTag + "."+ options.errorClass).remove();													//remove any previous error messages
				var curfield = eleme.parents(options.tagToUse+':first').find("label.required").text();			//get the label of the current field
				var errorMessage = curfield + ' is a required field';								//create a variable of the error message
				var radiocheckedcount=0																//create a counter set to 0
				jQuery(":radio",$listItem).each(function(){											//for each radio button in the same listitem 	
					if(jQuery(this).is(":checked")){																//if the radio is checked
						radiocheckedcount++														//add 1 to the counter (should really never reach more than 1 with radio buttons)
					}
				})
				if(radiocheckedcount==0){															//if the counter is still at 0 then no radio buttons were checked
					
					options.errorMessage = errorMessage				
					if(options.labelOutsideDiv){
						MENTOR.insertErrorMessage(options,$listItem,"append")
					}else{
						MENTOR.insertErrorMessage(options,$listItem,jQuery("*:last",$listItem))
					}

				}
			}

			if(eleme.is(":checkbox")){																	//if the required element is a checkbox
				$listItem.find(options.errorTag + "."+ options.errorClass).remove();													//remove any previous error messages
				var curfield = eleme.parents(options.tagToUse+':first').find("label.required").text();			//get the label of the current field
				var errorMessage = curfield + ' is a required field';								//create a variable of the error message
				var checkboxcheckedcount=0																//create a counter set to 0
				jQuery(":checkbox",$listItem).each(function(){											//for each checkbox in the same list item 	
					if(jQuery(this).is(":checked")){																//if the radio is checked
						checkboxcheckedcount++														//add 1 to the counter (should really never reach more than 1 with radio buttons)
					}
				})
				//return false;
				
				if(checkboxcheckedcount==0){															//if the counter is still at 0 then no checkboxes were checked
				
					options.errorMessage = errorMessage
					if(options.labelOutsideDiv){
						MENTOR.insertErrorMessage(options,$listItem,"append")
					}else{
						MENTOR.insertErrorMessage(options,$listItem,jQuery("*:last",$listItem))
					}

				}
				if(jQuery(".createdcheckother",$listItem).attr("checked")==true){
					if(jQuery(".checkboxother",$listItem).val()==''){
						if(options.labelOutsideDiv){
							var curfield = jQuery(".checkboxother",$listItem).parents("div:first").prev("p").find("label").text();			//get the label of the current field
						}else{
							var curfield = jQuery(".checkboxother",$listItem).prev("label").text();			//get the label of the current field
						}
						var errorMessage = curfield + ' is a required field';								//create a variable of the error message
						options.errorMessage = errorMessage
						MENTOR.insertErrorMessage(options,$listItem,jQuery(".checkboxother",$listItem))
					}
				}
			}
	
			if (eleme.attr("mgc:action")=="otherOption"){											//if this is a select field with an other afterward
				if(jQuery.trim(jQuery("option:selected",eleme).text())=='Other (please specify):') {							//if the other item is selected
					var $othertext = eleme.parent().find("span.showingoption").find("input")					//set a variable to hold the jquery object of the other text field
					if($othertext.val()==''){														//if the other text field is empty
						$othertext.next('p').remove();											//remove any previously created error messages
						var curfield = $othertext.parents("p").prev("select").prev('label').text();	//get the label of the current field
						var errorMessage = curfield + ' Other is a required field';					//create a variable of the error message
						options.errorMessage = errorMessage
						MENTOR.insertErrorMessage(options,$listItem,eleme)
					}else{																			//if the field is not blank
						$othertext.next('p').remove();											//remove error messages
						$listItem.removeClass('error');												//add the error class to the list item
					}
				}
			}

			if((eleme.is(":text") || eleme.is("textarea") || eleme.is("select") || eleme.is(":password") || eleme.is(":file"))&&((eleme.val() == '')||(eleme.val() == null))){																	//if the required input is empty

				var curfield;
				if(options.labelOutsideDiv){
					curfield = eleme.parents('div:first').prev("label").text();											//get the label of the current field
				}else{
					curfield = eleme.prev('label').text();											//get the label of the current field
				}
				var errorMessage = curfield + ' is a required field';								//create a variable of the error message
				
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessage(options,$listItem,eleme)

			}
	
			if(eleme.is('.' + options.emailClass)){																//if this is the email field
				if(eleme[0].value != '' && !/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(eleme[0].value)){			//if the field is not empty and fails the regular expression test
					var errorMessage = 'Please use proper email format (e.g. joe@example.com)';	//create the error messsage
				
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessage(options,$listItem,eleme)

				}
			}

			if(eleme.is('.' + options.limitClass)){																//if this is the phone field
				var limit=eleme.attr("rel")
				if(limit!=''&&!isNaN(limit)){
					limit=parseInt(limit,10);
					var ellength=parseInt((eleme.val()).length,10)
					if(ellength>limit){
						var errorMessage = 'Too many characters, please limit your input to ' + limit + ' characters. You entered ' + ellength + ' characters.';							//create the error messsage
				
						options.errorMessage = errorMessage
						MENTOR.insertErrorMessage(options,$listItem,eleme)
					}
				}
			}
			if(eleme.is('.' + options.phoneClass)){																//if this is the phone field
				if(eleme[0].value != '' && !/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(eleme[0].value)){					
																								//if the field is not empty and fails the regular expression test
					var errorMessage = 'Please enter a valid phone number';							//create the error messsage
				
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessage(options,$listItem,eleme)

				}
			}

			if(eleme.is('.' + options.numericClass)){																//if this is a field which should only be numeric (is marked by the class numeric)
				var curfield = eleme.prev('label').text();										//get the label of the current field
				if(eleme[0].value != '' && isNaN(eleme[0].value)){											//if the field is not empty and it is not a number
					var errorMessage = 'Please enter a numeric ' + curfield;						//create the error messsage
				
					options.errorMessage = errorMessage
					MENTOR.insertErrorMessage(options,$listItem,eleme)

				}
			}
		

			var numErrors = jQuery(options.errorTag + '.'+ options.errorClass, $listItem).length;											//count the number of errors
			if (numErrors>0){
				$listItem.addClass('error');														//add error class to parent list item
			}

		},
		insertErrorMessage: function(newoptions,$listItem,$insertAfterPoint){
			var prop = {
				errorTag: 'p',
				errorMessage: 'There is an error with this field.'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions)
			if(options.labelOutsideDiv){
				if($insertAfterPoint!="append"){
					$insertAfterPoint.parents("div:first").addClass("error")
				}
			}
			var $errmess = jQuery('<' + options.errorTag + '></' + options.errorTag + '>')								//create the paragraph that will hold the rror message
			.text(options.errorMessage)																//put the error message in the paragraph
			.addClass(options.errorClass)																//add the error class to the paragraph
			
			if($insertAfterPoint!="append"){
				$errmess.insertAfter($insertAfterPoint);															//insert the paragraph after the email field
			}else{
				$errmess.appendTo($listItem.find("td:first"))
			}

			$listItem.addClass('error');													//add error class to parent list item
		},


/* ********* AUTOCOMPLETE METHOD  **************** */



		autocomplete: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){
				jQuery(document).ready(function(){MENTOR.autocompleteprocess(options)})
			}else{
				MENTOR.autocompleteprocess(options)
			}
	
		},
		autocompleteprocess: function(newoptions){
			var prop = {
				autoFillTextReference: '#autofilltext',				//the selector for the element that the user is typing into
				container: '<ul class="autocomplete"></ul>',				//the container for the list of possible results
				attachContainerToText: 'yes',								//should the container be attached to the text field
				wrapperTag: 'li',											//the tag each possible result will be wrapped in
				wrapText: false,
				wrapTextOpen: '<a href="#">',
				wrapTextClose: '</a>',
				minChars: 1,												//minumum characters before results are returned
				jsonUrl: 'autojson.js',										//the url to get the json from
				highlightClass: 'selected',									//the class used for when a possible result is highlighted
				valueFn:function(datapass){									//the function to get results from the json
					var valuePass = datapass.FIRSTNAME + ' ' + datapass.LASTNAME;
					return valuePass;
				},
				onSelected:function(jsonmember,autoFill){							//function that gets called onselection of an item
				},
				paramName: 'value',											//value to use when passing value of textfield
				onShow: function(){},
				onHide: function(){},
				useSpinner: false,
				spinnerPath: '/images/anim-loading.gif'
			}
			var options = {};												//new object to  hold options
			jQuery.extend(options, prop, newoptions)						//overwrite defaul options with passed in options
			jQuery(options.autoFillTextReference).each(function(){
				var $autofilltext = jQuery(this);		//save a reference to the element being typed into
				var $autocomplete = jQuery(options.container).hide();			//hide the element which contains suggested values for the text field
				$autocomplete.insertAfter($autofilltext);						//insert the container after the text field
	
				var jsoncache;													//create a variable which will hold the returned json
				var autostatus = null;
				
				var selectedItem = null;										//make sure the selectedItem variable does not hold any previous references
				var setSelectedItem = function(item){							//function to select an item in the container
					selectedItem = item;										//set selecteditem to the passed in item index 
					if(selectedItem===null){									//if there is no selected item, hide the suggested items
						autostatus = null;
						$autocomplete.hide();
						options.onHide();
						return;
					}
					if (selectedItem < 0){										//if the passed item index is somehow negative
						selectedItem = 0;										//select the first item
					}
					if(selectedItem >= $autocomplete.find(options.wrapperTag).length){	//if the passed item index is greater than the number of options
						selectedItem = $autocomplete.find(options.wrapperTag).length-1;	//select the last item
					}
					jQuery(options.wrapperTag,$autocomplete).removeClass(options.highlightClass);	//remove all highligt classes from the suggested items
					$autocomplete.find(options.wrapperTag).eq(selectedItem).addClass(options.highlightClass);	//highlight the item at the passed index 
					if(options.attachContainerToText==='yes'){	//if the suggested items should be attached to the text field
						var attachcssoptions = {				//an object to set the css values of the suggested item container
							'width': $autofilltext.width()+'px',		//set the width of the container to the width of the text field
							'position':'absolute'				//set the position to absolute
						}
						$autocomplete.css(attachcssoptions);	//bind the css to the container element
					}
					if(autostatus=='on'){
						$autocomplete.show();	//show the container
						options.onShow();
					}
				}
		
				var populateSearchField = function(){			//function to populate the text field
					$autofilltext.val($autocomplete.find(options.wrapperTag).eq(selectedItem).text());  //set the value to value of the selected suggested item
					options.onSelected(jsoncache[selectedItem],$autofilltext)											//call the onselected function, pass thee json member for the selected item
					setSelectedItem(null);																//call the setSelectedItem function
				}
		
				var createDropItem = function(indexitem,valuepass,datapass){							//function which creates a suggestion in the container
					var $dropItem = jQuery('<' + options.wrapperTag + '></' + options.wrapperTag + '>');
					$dropItem.html(valuepass).mouseover(function(){										//create the item, set its value and bind a mouseover
						setSelectedItem(indexitem);														//mouseover highlights item
					}).click(function(){																//click populates field
						populateSearchField(datapass);
					}).appendTo($autocomplete);															//append the new item to the container
					if(options.wrapText){
						$dropItem.wrapInner(options.wrapTextOpen + options.wrapTextClose);
					}
				}
			
				$autofilltext.attr('autocomplete','off').keyup(function(event,a){							//add an autocomplete off attribute to the text field and bind a keyup event
					if($autofilltext.val().length >= options.minChars){									//if the user has typed in more characters than the minimum
						if (((event.keyCode > 40 || event.keyCode == 8)||(a === "mousepaste"))&&event.keyCode!==undefined){									//if the key pressed was not a special character or was the backspace
							autostatus = 'on';
							var ajaxDataObj = {};														//create a new Object	
							ajaxDataObj[options.paramName] = $autofilltext.val();						//add the value of the text field to the data being sent in the ajax query 
							if(options.useSpinner){
								$autocomplete.empty().append(('<' + options.wrapperTag + ' class="loading"><img src="' + options.spinnerPath + '" /></' + options.wrapperTag + '>')).show();
							}
							jQuery.ajax({																//the ajax query 
								'url': options.jsonUrl,													//the url being queried 
								'data': ajaxDataObj,													//the data being sent with the query 	
								'dataType': 'json',														//expecting json to be returned 
								'port': "autocomplete",													//identify this as so it can be aborted independently of other ajax queries
								'mode': "abort",														//if any ajax queries are made with the same port value, cancel this one 
								'type': 'GET',															//is a get request
								'success': function(data){												//on success of the query 
									jsoncache = null;													//clear out the cache of the json
									if(data.length){													//if results were returned
										jsoncache=data;													//store the results where other functions can access them
										$autocomplete.empty().hide();											//empty the suggestions container
										for(var i = 0,datal = data.length;i<datal;i++){								//loop through the json
											var valuetoshow=options.valueFn(data[i]);					//call the function to format the data to be shown
											createDropItem(i,valuetoshow);								//add the suggestion to the container
										}
										setSelectedItem(0);												//make the first item selected
									}else{
										setSelectedItem(null);											//or set the selected item to null if there were no results
									}
								}
							})
						}
						else if(event.keyCode == 38 && selectedItem !== null){							//if user presses up arrow
							if(selectedItem==0){
								setSelectedItem(jQuery("li",$autocomplete).length);
							}else{
								setSelectedItem(selectedItem - 1);											//select previous item
							}
							event.preventDefault();
						}
						else if(event.keyCode == 40 && selectedItem !== null) {							//if user presses down arrow
							if(selectedItem==(jQuery("li",$autocomplete).length-1)){
								setSelectedItem(0);
							}else{
								setSelectedItem(selectedItem + 1);											//select next item
							}
							event.preventDefault();
						}
						else if(event.keyCode == 27 && selectedItem !== null) {							//if user presses escape key
							setSelectedItem(null);															//if there are less characters than the minimum clear selected item
							event.preventDefault();
						}
					}else{
						setSelectedItem(null);															//if there are less characters than the minimum clear selected item
						event.preventDefault();
					}
				})
				
				$autofilltext.keypress(function(event){													//bind keypress event
					if(event.keyCode == 13){									//if user presses enter key
						event.preventDefault();
					}
					if(event.keyCode == 13 && selectedItem !== null){									//if user presses enter key
						populateSearchField();															//populate search field
						event.preventDefault();
					}
					if(event.keyCode == 9 && selectedItem !== null){									//if user presses enter key
						populateSearchField();															//populate search field
						event.preventDefault();
					}
					if(event.keyCode == 38 && selectedItem !== null){							//if user presses up arrow
						event.preventDefault();
					}
					else if(event.keyCode == 40 && selectedItem !== null) {							//if user presses down arrow
						event.preventDefault();
					}
				}).blur(function(){																		//bind blur event to text field
					setTimeout(function(){																//hide suggestions on blur but leave time for a click event
						setSelectedItem(null);
					}, 250);
				});
				
				var iePaste = function(){
					$autofilltext.trigger("keyup",["mousepaste"]);
				}
				if($.browser.msie){
					$autofilltext[0].onpaste=function(){setTimeout(iePaste,100)};                     
				}else if($.browser.mozilla){
					$autofilltext[0].addEventListener('input',function(){$autofilltext.trigger("keyup",["mousepaste"]);},false);
				}
			});
		},

/* ********* DATALIST METHOD  ***************** */


		createdatalist: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){
				jQuery(document).ready(function(){MENTOR.createdatalistprocess(options)})
			}else{
				MENTOR.createdatalistprocess(options)
			}
	
		},
		createdatalistprocess: function(newoptions){
			var prop = {
				listurl: 'server',																	//this is the url to query for the table structure in server mode.
				listdata:{somedata: 'data'}, 														//data to be posted when querying for table for list
				dataurl:'server',																	//url to be queried for table
				tablesdata: {somedata: 'data'},														//data to be posted when querying for table for list item.
				target: 'div.copy',																	//The selector for where the list should be appended
				expandedClass: "expanded",
				closedClass: "expandable",
				listclass: 'datalist',																//The class to be added to the list
				listId: 'dg1',																		//The ID to be added to the list, is important if there is going to be more than one grid on a page.	
				onlistload: function(){},											//A function that fires when the list loads
				oncollapse: function(path){return path},											//A function that fires when a row is collapsed and is passed the path to that row
				onexpand: function(path,datareq){return path},										//A function that fires when a row is expanded and is passed the path to that row
				ondataload: function(path){return path},										
				loadingImageList: '/marketing/images/anim-loading.gif',							//The image to use when the table is loading.
				loadingImageRow: '/marketing/images/anim-loading-sm.gif',							//The image to use to show rows are loading
				openSingleRows: 'no',
				targetFill: "div.fill",
				ieWarningPrepend: 'td.flash',
				idparam: "recordid",
				alternateEl: "span.companyname"
			}
			var options = {};
			jQuery.extend(options, prop, newoptions);

			//remove loading image
			jQuery("#"+options.listId+'Loader').remove();
			jQuery(window).unload(function(){
				jQuery(options.target).empty();
			})
			jQuery(options.target).empty();
			
			
			MENTOR.createloading({loadingTargetSelector: options.target,loadingId:options.listId+'Loader',loadingImage:options.loadingImageList});
																									//create loading image
			jQuery('.error').remove();																//remove any error messages
			
			//ie 6 warning
			if((jQuery.browser.msie)&&(parseInt(jQuery.browser.version)==6)){
				jQuery("#ie6warning").remove();
				jQuery(options.ieWarningPrepend).prepend('<div class="ie6error" id="ie6warning">You may experience poor performance while using IE6.  To improve performance you can upgrade to <a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx" target="_blank">IE7</a>. <a href="#" id="ie6warninglink">hide this error</a></div>');
				jQuery("#ie6warninglink").click(function(){
					jQuery("#ie6warning").remove();
					return false;
				})
			}
			
			
			options.listdata['listId']=options.listId;										//add the table id to data being posted for table structure
			jQuery.ajax({																		//create ajax query 
				dataType: 'html',																//expect html
				port: options.listId,															//create id for the ajax query so that if another is started this is cancelled
				mode: "abort",																	//abort this query if another is started with same port
				url: options.listurl,														//url to post to 
				type: 'POST',																	//is a post	
				data: options.listdata,														//data to post
				error: function(){																//if there is an error
					jQuery("#"+options.listId+"Loader").remove();								//remove the loader
					jQuery(options.target).prepend('<div class="error">There was an error loading the list, please try again.</div>')
																								//add error message
				},
				success: function(data){														//on success
					jQuery("#"+options.listId+"Loader").remove();						//remove loader
					//var listStatus = {}
					var target = jQuery(options.target)[0]
					target.innerHTML=data;
					options.onlistload();
					jQuery("ul",target).click(function(e){
						var $target=jQuery(e.target);
						if($target.is(options.alternateEl)){
							$target=$target.parent("li");
						}
						if($target.is("li")){
							var rowclicked = $target.attr("rel");
							var $filler = $target.find(options.targetFill);
							if($target.hasClass(options.closedClass)){
								if(!($target.parents(options.targetFill).length)){
									$target.removeClass(options.closedClass).addClass(options.expandedClass);
									options.onexpand(rowclicked,!($filler.is(".filled")));
									if($filler.is(".filled")){
										$filler.show();
									}else{
										var $loadingRow = jQuery('<div class="loading"><img src="' + options.loadingImageRow + '"></div>');	
																											//create the loading tr with the correct colspan
										$filler.html($loadingRow)					//insert the loading row after the clicked row
										$filler.show();
										options.tablesdata[options.idparam]=rowclicked;	
										$.ajax({
											dataType: 'html',																//expect html
											url: options.dataurl,														//url to post to 
											type: 'POST',																	//is a post	
											data: options.tablesdata,														//data to post
											error: function(){																//if there is an error
												jQuery("#"+options.listId+"Loader").remove();								//remove the loader
												$filler.html('<div class="error">There was an error loading the list, please try again.</div>')
																															//add error message
											},
											success: function(data){														//on success
												$filler.html(data).addClass("filled")
												options.ondataload(rowclicked);
											}
										});
									}
								}
							}else if($target.hasClass(options.expandedClass)){
								if(!($target.parents(options.targetFill).length)){
									$target.removeClass(options.expandedClass).addClass(options.closedClass);
									$filler.hide();
									options.oncollapse(rowclicked);
								}
							}
						}
					})
				}
			})
		},
/* ********* DATAGRID METHOD  ***************** */


		createdatagrid: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){
				jQuery(document).ready(function(){MENTOR.createdatagridprocess(options)})
			}else{
				MENTOR.createdatagridprocess(options)
			}
	
		},
		createdatagridprocess: function(newoptions){
			var prop = {
				htmlSource: 'server',																//Can be server or xml, if it is server the table structure is returned from the server, if it is xml than the browser builds the table from the returned xml.
				structureurl: 'server',																//this is the url to query for the table structure in server mode.
				urls: ['datagrid.xml','datagrid.xml','datagrid.xml'],								//An array of urls to query for each level of the datagrid
				structure: {somedata: 'data'},														//An object that contains the data to be posted when querying for the table structure in server mode.
				data: [{somedata: 'data'},{somedata: 'data'},{somedata: 'data'}],					//An array of objects that contain the data to be posted when querying for each level of the grid.
				target: 'div.copy',																	//The selector for where the table should be appended
				tableclass: 'datagrid',																//The class to be added to the table
				tableId: 'dg1',																		//The ID to be added to the table, is important if there is going to be more than one grid on a page.	
				onrowsload: function(path){return path},											//A function that fires when a set of rows successfully loads currently only in server mode
				ontableload: function(){},															//A function that fires when the table loads with its first set of data in server mode
				oncollapse: function(path){return path},											//A function that fires when a row is collapsed and is passed the path to that row
				onexpand: function(path,datareq){return path},										//A function that fires when a row is expanded and is passed the path to that row
				ids: ['foo','foo','foo'],															//This is an array containing a value for each level of the datagrid, it is used to pass the unique id for that level.
				loadingImageTable: '/marketing/images/anim-loading.gif',							//The image to use when the table is loading.
				ieWarningPrepend: 'td.flash',
				loadingImageRow: '/marketing/images/anim-loading-sm.gif',							//The image to use to show rows are loading
				classForHiddenRows: 'seeall',
				openSingleRows: 'no'
			}
			var options = {};
			jQuery.extend(options, prop, newoptions);

			//remove loading image
			jQuery("#"+options.tableId+'Loader').remove();
			
			
			MENTOR.createloading({loadingTargetSelector: options.target,loadingId:options.tableId+'Loader',loadingImage:options.loadingImageTable});
																									//create loading image
			jQuery('.error').remove();																//remove any error messages
			
			//ie 6 warning
			if((jQuery.browser.msie)&&(parseInt(jQuery.browser.version)==6)){
				jQuery("#ie6warning").remove();
				jQuery(options.ieWarningPrepend).prepend('<div class="ie6error" id="ie6warning">You may experience poor performance while using IE6.  To improve performance you can upgrade to <a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx" target="_blank">IE7</a>. <a href="#" id="ie6warninglink">hide this error</a></div>');
				jQuery("#ie6warninglink").click(function(){
					jQuery("#ie6warning").remove();
					return false;
				})
			}

			if(options.htmlSource==='xml'){															//if the mode is xml

				jQuery.ajax({
					dataType: 'xml',																//expect xml
					url: options.urls[0],															//use the first url in the urls Array
					type: 'POST',																	//make it a post
					port: options.tableId,															//set an id for this ajax call so it can be cancelled when another is started
					mode: "abort",																	//abort this ajax query if any with the same port are started
					data: options.data,																//what to post to url
					success: function(data){														//on success of the query 
						var $data = jQuery(data);													//put the xml into a jquery object 
						var numColumns = jQuery("row:first column",$data).length					//count how many columns will be needed in the table
						var numSeries = jQuery("row[type!='header']:first column:first series",$data).length	//count how many series there will be in the table
						options[numColumns]=numColumns;												//add numseries and numcolumns to the options object 
						options[numSeries]=numSeries;
						
						jQuery("datagrid", $data).each(function(){									//start to build table, for each datagrid node in the xml
							var $this = jQuery(this)												//create a reference to the current datagrid
							var $datagrid = jQuery('<table width="100%" cellspacing="0" class="' + options.tableclass + '" id="' + options.tableId + '"></table>')
																									//create a table for the current datagrid

							$datagrid.append('<colgroup><col /></colgroup>')						//build colgroups
							var $colgroup
							for(i=0;i<numColumns;i++){												//for each column
								$colgroup=jQuery('<colgroup></colgroup>')							//add a colgroup
								for(var j=0;j<numSeries;j++){										//for each series
									var colclass="series_"+(j+1);									//create a class for that series		
									jQuery('<col />').addClass(colclass).appendTo($colgroup);		//append a col to the colgroup for current column
								}
								$colgroup.appendTo($datagrid)										//append colgroups to table
							}
			
							//build thead
							var $thead=jQuery("<thead></thead>")
							var $firstheadrow=jQuery("<tr></tr>")
							
							var $titlecell;
							
							
							if(jQuery("row[type='headrow']",$this).length===1){						//if there is a second row in the header grab that data here
								$titlecell=jQuery('<th rowspan="2" class="first"></th>').append($this.attr("title")).appendTo($firstheadrow);
																									//add the title of the datagrid to the first cell in the header
								
								var $secondheadrow=jQuery('<tr></tr>')								//create second header row
								var seriescount=0;													//create a series counter
								jQuery("row[type='headrow'] column series",$this).each(function(){	//for each series node in a headrow
									seriescount++;													//add 1 to series counter
									if(seriescount===numSeries+1){									//if series counter = 1 more than the number of series
										seriescount=1;												//set the counter back to 1
									}
									var colclass="series_"+seriescount;								//create a class indicating the series
									jQuery('<td></td>').append(jQuery(this).text()).addClass(colclass).appendTo($secondheadrow);
																									//add a cell to the row with the correct series class
								})
								var appendsechead = "yes"											//set a reference for future use that there is a second header row
							}else{
								$titlecell=jQuery('<th class="first"></th>').append($this.attr("title")).appendTo($firstheadrow);
																									//if there is only 1 header row, add the title to the first cell
							}
			
							jQuery("row[type='header'] column",$this).each(function(){				//for each column in header row
								jQuery('<th colspan="' + numSeries +'" style="background: #fff"></th>').append(jQuery(this).attr("title")).appendTo($firstheadrow);
																									//add the header cells
							})
							
							$firstheadrow.appendTo($thead)											//append the first header row to the thead
			
							if(appendsechead === "yes"){											//if there is a second header row, append it to the thead
								$secondheadrow.appendTo($thead)
							}
			
							$thead.appendTo($datagrid)												//append the thead to the datagrid
							
							//build tbody
							var $tbody = jQuery('<tbody></tbody>');									//create the tbody
											
							jQuery("row[type='data']",$this).each(function(){						//for each data row in the xml
								var $newrow = jQuery('<tr rel="' + jQuery(this).attr("id") + '"></tr>');	//create a new row with the proper path in the rel tag 
								var $firstcell = jQuery('<td class="first"></td>')					//create the first cell for the new row
								$firstcell.append(jQuery(this).attr("title"))						//add the name of the row in the first cell
								if(jQuery(this).attr("haschildren")==="yes"){						//if the row has children
									$newrow.addClass("dg_expandable").addClass("firstlevel");		//add expandable class and add the class firstlevel
									$firstcell.addClass("dg_firstcellexpandable")					//add expandable class to the first cell of the row as well
									$newrow.toggle(function(){										//add a toggle event to the new row
										$clickedrow=jQuery(this);									//save a reference to the currently clicked row
										options.onexpand($clickedrow.attr("rel"));					//call the onexpand function on first click and send path with it 
										$clickedrow.removeClass("dg_expandable").addClass("dg_expanded")	//remove the expandable class and add the expanded class
										if(jQuery("tr[rel^='" + $clickedrow.attr("rel") + ".']").length >0){	//if the rows children already exist
											jQuery("tr[rel^='" + $clickedrow.attr("rel") + ".']").each(function(){	//for each of the child rows
												var currentpath = jQuery(this).attr("rel")			//save a reference to the current path
												if(currentpath.split('.').length<3){				//if the current row is a second level row
													jQuery(this).show()								//show the row
													if(jQuery(this).hasClass("dg_expanded")){		//if the row has the expanded class
														jQuery(this).trigger("click");				//trigger a click so that it is in its correct state
													}
												}
											});
										}else{														//if the rows children do not already exist
											var totalCols = (options.numColumns*options.numSeries)+1;	//find the number of total columns
											var $loadingRow = jQuery('<tr><td colspan="' + totalCols + '"><img src="' + options.loadingImageRow + '"></td></tr>');	
																									//create the loading tr with the correct colspan
											$loadingRow.insertAfter($clickedrow)					//insert the loading row after the clicked row
											options.data[1][options.ids[1]]=$clickedrow.attr("rel")	//add the clicked row id to the data to be posted	
											jQuery.ajax({											//create an ajax query 
												dataType: 'xml',									//expect xml to be returned
												type: 'POST',										//is a post
												port: $clickedrow.attr("rel"),						//set an id for the query so it can be aborted
												mode: "abort",										//abort if any queries with the same port are started
												data: options.data[1],								//send the 2nd data object 
												url: options.urls[1],								//post to the 2nd url
												success: function(data){							//upon success
													$loadingRow.remove();							//remove the loading row
													MENTOR.getnewrows(data,$clickedrow[0],$clickedrow.attr("rel"),options,'second');
																									//get new rows passing loaded xml, clicked row, clicked path, options and level
												}
											});
										}	
									},function(){													//on second click
										var $clickedrow=jQuery(this);								//save reference to clicked row
										jQuery(this).removeClass("dg_expanded").addClass("dg_expandable")	//remove expanded class, add expandable class
										jQuery("tr[rel^='" + jQuery(this).attr("rel") + ".']").hide();		//hide child rows
										options.oncollapse($clickedrow.attr("rel"))							//call oncollapse function
									})
								}
								$firstcell.appendTo($newrow);										//append the first cell to the new row
								seriescount=0;														//set the series counter to 0
								jQuery("series",jQuery(this)).each(function(){						//for each series
									seriescount++;													//add 1 to the series counter
									if(seriescount===numSeries+1){									//if the series counter is one more than the number of series
										seriescount=1;												//reset series counter to 1
									}
									var colclass = "series_"+seriescount;							//create a class for the series
									jQuery('<td></td>').addClass(colclass).append(jQuery(this).text()).appendTo($newrow);
																									//add cell with correct series class
								});
								$newrow.appendTo($tbody);											//append new row to the tbody
							})
							$tbody.appendTo($datagrid)												//append the tbody to thee datagrid
							
							//remove loading image
							jQuery("#"+options.tableId+'Loader').remove();							//remove the loading image
	
							jQuery('#'+options.tableId).remove();									//remove previous datagrid
							//append the table
							$datagrid.appendTo(jQuery(options.target))								//append the table
						})
					}
				});
			}else if(options.htmlSource==='server'){												//if the mode is server
				
				options.structure['tableId']=options.tableId;										//add the table id to data being posted for table structure
				jQuery.ajax({																		//create ajax query 
					dataType: 'html',																//expect html
					port: options.tableId,															//create id for the ajax query so that if another is started this is cancelled
					mode: "abort",																	//abort this query if another is started with same port
					url: options.structureurl,														//url to post to 
					type: 'POST',																	//is a post	
					data: options.structure,														//data to post
					error: function(){																//if there is an error
						jQuery("#"+options.tableId+"Loader").remove();								//remove the loader
						jQuery(options.target).prepend('<div class="error">There was an error loading the table, please try again.</div>')
																									//add error message
					},
					success: function(data){														//on success
						var $returnedTable=jQuery(data);											//save a reference to the returned table
						$returnedTable.attr({														//set the attributes on the table
							width: '100%',
							cellspacing: 0
						}).addClass(options.tableclass);
						jQuery.ajax({																//create another ajax query 
							dataType: 'html',														//expect html
							url: options.urls[0],													//url to post to for first levels
							type: 'POST',															//is a post
							error: function(){														//if there is an error
								jQuery("#"+options.tableId+"Loader").remove();						//remove loader
								jQuery(options.target).prepend('<div class="error">There was an error loading the table, please try again.</div>')
																									//add error message
							},
							port: options.tableId,													//create id for the ajax query so that if another is started this is cancelled
							mode: "abort",															//abort this query if another is started with same port
							data: options.data[0],													//data to post
							success: function(data){												//on success	
								var $returnedRows=jQuery(data);										//create reference to the returned rows
								$returnedRows.each(function(){									//for each returned row
									var $currentRow=jQuery(this);									//create reference to current row
									if($currentRow.is(".tablehead")){								//if is a tableheader
										jQuery("td", $currentRow).each(function(index){				//add values from first row to header
											if(index>0){											
												jQuery("thead td:eq(" + (index-1) + ")", $returnedTable).text(jQuery(this).text())
											}
										});
									}else{															//if current row is not tablehead
										$currentRow.appendTo(jQuery("tBody",$returnedTable))		//just append it to tbody of returned table
									}
								});
								jQuery("tr.dg_expandable td.first",$returnedTable).addClass("dg_firstcellexpandable");	//add expandable class to first cell of expandable rows
								jQuery('#'+options.tableId).remove();								//remove previous datagrid
								jQuery("#"+options.tableId+"Loader").remove();						//remove loader
								$returnedTable.appendTo(jQuery(options.target));					//append the table to the target
								options.ontableload();											//call table load function
								MENTOR.dg_rowevents(1,options,null);								//call dg_rowevents to bind events to the rows, pass level, options object an null for clicked since this is the first level and nothing was clicked
							}
						})
					}
				})

			}
		},	
		dg_rowevents: function(level,options,clicked){												//function to bind events to rows of datagrid in server mode
			var selectString;																		//create variable to store selector string for rows binding events
			var $passedTable = jQuery("#" + options.tableId)										//store jQuery object of datagrid table
			if(level===1){																			//if is first level just get expandable rows
				selectString="tr.dg_expandable"
			}else{																					//if is not first level, get children of clicked row
				selectString="tr.dg_expandable.level_"+level+"[rel^='" + clicked + ".']"
			}
			jQuery(selectString,$passedTable).each(function(){										//for each of the rows going to bind events to 
				jQuery(this).toggle(function(){														//bind toggle event
					var $currentClickRow = jQuery(this);											//save reference to clicked row
					var currentRel = $currentClickRow.attr("rel");									//save reference to path to clicked row
					var relArray = currentRel.split(".")											//create an array of items in path to clicked row
					var currentClickRowLevel=relArray.length;										//save a reference to the length of items in the path of current clicked row
	
					options.onexpand(currentRel,(jQuery("tr[rel^='" + $currentClickRow.attr("rel") + ".']").length==0));
																									//call onexpand function and pass path of expanded and whether or not data was requested (boolean)
					$currentClickRow.removeClass("dg_expandable").addClass("dg_expanded")			//remove expandable class and add expanded class
					if(jQuery("tr[rel^='" + $currentClickRow.attr("rel") + ".']").length >0){		//if the child rows already exist 
						jQuery("tr[rel^='" + $currentClickRow.attr("rel") + ".']").each(function(){	//for each of the child rows
							var currentpath = jQuery(this).attr("rel");								//save a reference to the current path
							if(currentpath.split('.').length<(currentClickRowLevel+2)){				//if the row is the next level from the clicked row
								if(!(jQuery(this).hasClass(options.classForHiddenRows))){
									jQuery(this).show();												//show the row
									if(jQuery(this).hasClass("dg_expanded")){							//if a row has the expand class
										jQuery(this).trigger("click").trigger("click");					//trigger a click
									}
								}
							}
						});
					}else{																			//if child rows do not already exist
						var totalCols = jQuery("tbody tr:first td",$passedTable).length;			//get the total number of columns to use in colspan
						$currentClickRow.next("tr.loading").remove();								//remove any existing loading row
						var $loadingRow = jQuery('<tr class="loading"><td colspan="' + totalCols + '"><img src="' + options.loadingImageRow + '"></td></tr>');	
																									//create the loading tr
						$loadingRow.insertAfter($currentClickRow)
																									//insert loading row
						options.data[level][options.ids[level]]=currentRel.split(".")[level-1];
																									//add level unique id to level data object 
						if(level>1){																//if the level is not the first level
							options.data[level][options.ids[level-1]]=currentRel.split(".")[level-2];	//add parent level unique id
						}
						jQuery.ajax({																//create ajax query 
							dataType: 'html',														//expect html
							type: 'POST',															//is a post
							port: currentRel,														//create port id
							mode: "abort",															//abort query if another query with same port is started
							data: options.data[level],												//data to post
							url: options.urls[level],												//url to post to 
							error: function(){														//if there is an error
								jQuery("td",$loadingRow).html('<div class="error">There has been an error loading these rows.  Please try again.</div>');
																									//add error message
							},
							success: function(data){												//upon success
								$loadingRow.remove();												//remove loading row
								var $rowResult = jQuery.trim(data);
								var datasplit = $rowResult.split("</tr>")
								datasplit.pop();
								var $currentRow = $currentClickRow;
								var $rowSet;
								jQuery.each(datasplit,function(i,val){
									var $rowResult2 = jQuery(val+"</tr>");
									if($rowResult2.hasClass(options.classForHiddenRows)){
										$rowResult2.hide();
									}
									if(i==0){
										$rowSet=$rowResult2;
									}else{
										$rowSet=$rowSet.add($rowResult2);
									}
									$rowResult2.insertAfter($currentRow);			//insert the new rows before it 
									$currentRow = $currentRow.next("tr");
									if($currentClickRow.is(".dg_expandable")){							//if the parent row has been closed while loading new rows
										$rowSet.hide();												//hide the new rows
										$rowResult2.hide();
									}
								})
								var addClassSelect = "tr.dg_expandable.level_" + (level+1) + " td.first"		//create selector to add expandable class
								jQuery(addClassSelect,$passedTable).addClass("dg_firstcellexpandable");	//add expandable class to first cell of new rows
								options.onrowsload(currentRel);										//call onrowsload function
								MENTOR.dg_rowevents(currentClickRowLevel+1,options,currentRel);		//call this function again for new rows
							}
						});
					}	
	
				},function(){																		//on second click
					var $clickedrow=jQuery(this);													//create a reference to clicked row
					$clickedrow.next(".loading").remove();											//remove any next loading rows
					jQuery(this).removeClass("dg_expanded").addClass("dg_expandable")				//remove expanded class, add expandable class
					jQuery("tr[rel^='" + jQuery(this).attr("rel") + ".']").hide();					//hide child rows
					options.oncollapse($clickedrow.attr("rel"))										//call oncollapse function and pass path to collapsed row
				});
			});
			if(options.openSingleRows=='yes'){
				if(level===1 && (jQuery(selectString,$passedTable).length===1)){						
					jQuery(selectString,$passedTable).trigger("click")
				}
			}
		},
		getnewrows: function(data,objectafter,parent,options,step){									//function to get new rows for xml mode of create datagrid
			var $data = jQuery(data);																//add xml to jquery object 
			var $previousrow = jQuery(objectafter);													//create a reference to the object we are inserting new rows after
			jQuery("row[type='data']",$data).each(function(){										//for each data row in the xml
				var $newrow = jQuery('<tr rel="' + parent + '.' + jQuery(this).attr("id") + '"></tr>');	//create a new row with the correct path
				if(jQuery(objectafter).hasClass("level_1")){										//add the correct level class to the new row
					$newrow.addClass("level_2")
				}else if(jQuery(objectafter).hasClass("level_2")){
					$newrow.addClass("level_3")
				}
				var $firstcell = jQuery('<td class="first"></td>')									//create the first cell in the new row
				$firstcell.append(jQuery(this).attr("title"))										//add the row title to the first cell
				if(jQuery(this).attr("haschildren")==="yes"){										//if the row has children
					$newrow.addClass("dg_expandable");												//add expandable class
					$firstcell.addClass("dg_firstcellexpandable")									//add expandable class to first cell
					if(step==='second'){															//if is the second level
						$newrow.toggle(function(){													//add toggle event
							$clickedrow=jQuery(this);												//save a reference to the current row
							options.onexpand($clickedrow.attr("rel"));								//call the onexpand function when clicked first 
							$clickedrow.removeClass("dg_expandable").addClass("dg_expanded")		//remore the expandable class and add the expanded class
							if(jQuery("tr[rel^='" + $clickedrow.attr("rel") + ".']").length >0){	//if the children already exist
								jQuery("tr[rel^='" + $clickedrow.attr("rel") + ".']").show();		//show the children
							}else{																	//if the children dont exist
								var totalCols = (options.numColumns*options.numSeries)+1;			//total columns to use in colspan
								var $loadingRow = jQuery('<tr><td colspan="' + totalCols + '"><img src="' + options.loadingImageRow + '"></td></tr>');	//create the loading tr
																									//create loading row
								$loadingRow.insertAfter($clickedrow)								//insert the loading row
								var secondaryidpass=$clickedrow.attr("rel")							//create a reference to the id to pass
								options.data[2][options.ids[1]]=secondaryidpass.split('.')[0];		//add the parent id to the data being posted
								options.data[2][options.ids[2]]=secondaryidpass.split('.')[1];		//add the current level id to the data being posted
								jQuery.ajax({														//create an ajax query 
									dataType: 'xml',												//expect xml
									type: 'POST',													//is a post
									port: $clickedrow.attr("rel"),
									mode: "abort",
									data: options.data[2],
									url: options.data[2],
									success: function(data){
										$loadingRow.remove();										//remove loading rows
										MENTOR.getnewrows(data,$clickedrow[0],$clickedrow.attr("rel"),options,'third');
																									//call this function again
									}
								});
							}	
						},function(){																//on second click
							var $clickedrow=jQuery(this);											//save a reference to the clicked row
							jQuery(this).removeClass("dg_expanded").addClass("dg_expandable");		// remove expanded class and add expandable class
							jQuery("tr[rel^='" + jQuery(this).attr("rel") + ".']").hide();			//hide child rows
							options.oncollapse($clickedrow.attr("rel"))								//call oncollapse functions
						})
					}
				}
				$firstcell.appendTo($newrow);														//append first cell to the new row
				jQuery("series",jQuery(this)).each(function(){										//for each series in the xml row
					jQuery('<td></td>').append(jQuery(this).text()).appendTo($newrow);				//add a cell
				});
				$newrow.insertAfter($previousrow);													//insert new row after the previousrow 	
				$previousrow=$newrow;																//set the previous row variable so the next new row is inserted correctly
			})
		},
		
		
/* ********* CREATELOADING METHOD  **************** */



		createloading: function(newoptions){
			var prop = {
				loadingId: 'loadingtable',														// the id that will be added to the created table
				loadingTargetSelector: 'body',													// what the loading indicator will appear over
				loadingImage: '/marketing/images/anim-loading.gif'								// the image to use as the loading indicator
			}
			var options = {};
			jQuery.extend(options, prop, newoptions);											//overwrite the default options with any passed in options

			var $loadingImage=jQuery('<img class="dg_loadingimage" src="' + options.loadingImage + '">');	//creating the img

			var $loadingTarget = jQuery(options.loadingTargetSelector);							//the object that the  indicator will appear over

			var loadingTargetOffset =  $loadingTarget.offset()									//find the position of the element the indicator will appear over
			
			var $containTable = jQuery('<table id="' + options.loadingId + '" border="0" cellspacing="0" cellpadding="0"><tr><td></td></tr></table>');
																								//the table that will hold the indicator
			$containTable.css({																	//the css for the table
				'position': 'absolute',
				'left':loadingTargetOffset.left+'px',
				'top':loadingTargetOffset.top+'px'
			})
			jQuery("td",$containTable).css({													//the css for the td in the table
				'height': $loadingTarget.outerHeight(),
				'width': $loadingTarget.outerWidth(),
				'vertical-align': 'middle',
				'text-align': 'center'
			}).append($loadingImage);

			jQuery("body").append($containTable);

		},	
/* ********* MENTORSLIDER METHOD  ***************** */


		mentorslider: function(newoptions){
			var prop = {													//the default properties
				fireWhen: 'onready'											//when to execute the code
			}
			var options = {};												//new object 
			jQuery.extend(options, prop, newoptions)						//extend the prop object with the newoptions object to create the options object 
			if(options.fireWhen==='onready'){
				jQuery(document).ready(function(){MENTOR.mentorsliderprocess(options)})
			}else{
				MENTOR.mentorsliderprocess(options)
			}
	
		},
		mentorsliderprocess: function(newoptions){
			var prop = {
				containerselector: '.mentorslider',
				panelselector: '.mentorsliderpanel',
				easeTime: 750,
				easeFunc: "easeInOutExpo",
				activeClass: "current",
				rotateClass: "rotator",
				rotateSpeed: 2500,
				starterClass: "starthere",
				leftArrowClass: "ms_leftarrow",
				rightArrowClass: "ms_rightarrow",
				numberNavClass: "ms_numbernav",
				numberNavWrapClass: "ms_numbernavwrap",
				viewportClass: "ms_viewport",
				panelContainerClass: "ms_panelcontainer",
				widthOnUl: 'no',
				np_noshow: false
			}
			var options = {};
			jQuery.extend(options, prop, newoptions);
	
			
			jQuery(options.containerselector).each(function(){
					
				var $currSlider = jQuery(this);
				var $containEl = $currSlider.parents("div:first");
				var isscreenshotgallery=false;
				var ishighlights=false;
				if($containEl.hasClass("noshownav")){
					options.np_noshow=true;
				}
				if($containEl.hasClass("gallery")){
					isscreenshotgallery=true;
				}
				if($containEl.hasClass("highlights")){
					ishighlights=true;
				}
				var $panels = jQuery('div'+options.panelselector,$currSlider);
				var isFader=false;
				var numPanels = $panels.length;
				if($containEl.hasClass("fader")){
					isFader=true;
					$panels.slice(1,numPanels).hide()
					$panels.each(function(i){
						jQuery(this).css({'z-index':numPanels-i})
					})
				}
				var shownav=true;
				var numPanels = $panels.length;
				if((numPanels===1)&&(options.np_noshow)){
					shownav=false;
				}
				var $leftArrow = jQuery('<div class="' + options.leftArrowClass + '"><a href="#"></a></div>');
				var $rightArrow = jQuery('<div class="' + options.rightArrowClass + '"><a href="#"></a></div>');
				if(!isscreenshotgallery&&shownav){
					$rightArrow.insertAfter($currSlider)
					$leftArrow.insertAfter($currSlider)
				}
				var $numberNav = jQuery('<ul class="' + options.numberNavClass + '"></ul>')
				var defaultSelected=false;
				var currPanel = 1;
				jQuery('div'+options.panelselector,$currSlider).wrapAll('<div class="' + options.viewportClass + '"></div>').wrapAll('<div class="' + options.panelContainerClass + '"></div>').each(function(index){
					if(jQuery(this).hasClass(options.starterClass)){
						defaultSelected=true;
						currPanel=index+1;
					}
					$numberNav.append('<li><a href="#" class="progress">' + (index+1) + '</a></li>');
				});
				if(isscreenshotgallery&&shownav){
					jQuery("<li></li>").append($leftArrow).prependTo($numberNav)
					jQuery("<li></li>").append($rightArrow).appendTo($numberNav)
				}
				var panelWidth;
				if(jQuery.browser.safari){
					panelWidth = $currSlider.attr("rel").length>0 ? $currSlider.attr("rel") : parseInt(jQuery('div'+options.panelselector+':first',$currSlider).outerWidth());
				}else{
					panelWidth = parseInt(jQuery('div'+options.panelselector+':first',$currSlider).outerWidth())
				}
				var $panelContainer = jQuery("div."+options.panelContainerClass,$currSlider)
				jQuery("a.progress:first",$numberNav).addClass(options.activeClass);
				if(isscreenshotgallery||ishighlights){
					var panheightrun=function(){
						var panheight=jQuery('div'+options.panelselector,$currSlider).eq(0).outerHeight();
						jQuery('div.'+options.viewportClass,$currSlider).stop().animate({ height:panheight}, options.easeTime, options.easeFunc);
					}
					if(jQuery.browser.safari){
						setTimeout(panheightrun,500)
					}else{
						panheightrun()
					}
				}
				
				var removeFilter=function(element) {
					if(element.style.removeAttribute){
						element.style.removeAttribute('filter');
					}
				}
				//function to move the panels
				var movePanel = function(panel){
					if(isFader){
			            jQuery('div'+options.panelselector+':visible',$currSlider).fadeOut("normal");
        			    $panels.eq(panel).fadeIn("normal", function() {
							removeFilter(jQuery(this)[0]);
						});
					}else{
						var leftPos = (panel*panelWidth)*-1;
						$panelContainer.stop().animate({ left: leftPos}, options.easeTime, options.easeFunc);
						if(isscreenshotgallery||ishighlights){
							var panheight=jQuery('div'+options.panelselector,$currSlider).eq(panel).outerHeight();
							jQuery('div.'+options.viewportClass,$currSlider).stop().animate({ height:panheight}, options.easeTime, options.easeFunc);
						}
					}
				};
				
				//called when ever the user causes rotation
				var useraction = function(){
					if($currSlider.data("rotating")){
						$currSlider.trigger("mouseover");
					}
				};
				
				//events for numeric nav
				jQuery("a.progress",$numberNav).each(function(index){
					jQuery(this).click(function(){
						useraction();
						jQuery("a",$numberNav).removeClass(options.activeClass);
						jQuery(this).addClass(options.activeClass);
						currPanel = index+1;
						movePanel(index);
						return false;
					});					
				})
				
				var addclassSelector;
				
				if(shownav){
					//left arrow event
					jQuery("a",$leftArrow).click(function(){
						useraction();
						if(currPanel==1){
							currPanel=numPanels;
						}else{
							currPanel--;
						}
						jQuery("a",$numberNav).removeClass(options.activeClass);
						addclassSelector="a.progress:eq(" + (currPanel-1) + ")"
						jQuery(addclassSelector,$numberNav).addClass(options.activeClass);
						movePanel(currPanel-1);
						return false;
					});
					
					//right arrow event
					jQuery("a",$rightArrow).click(function(){
						useraction();
						if(currPanel==numPanels){
							currPanel=1;
						}else{
							currPanel++;
						}
						jQuery("a",$numberNav).removeClass(options.activeClass);
						addclassSelector="a.progress:eq(" + (currPanel-1) + ")"
						jQuery(addclassSelector,$numberNav).addClass(options.activeClass);
						movePanel(currPanel-1);
						return false;
					});
				}
				var $numberNavWrap=jQuery('<div class="' + options.numberNavWrapClass + '"></div>');
				$numberNavWrap.append($numberNav);
				if(shownav){
					$currSlider.append($numberNavWrap);
				}
				$panelContainer.width(panelWidth*numPanels);
				
				var navWidth=numPanels*2;
				
				var setnavWidth = function(){
					jQuery("li",$numberNavWrap).each(function(){
						navWidth+=jQuery(this).width();
					})
					if(options.widthOnUl=='no'){
						$numberNavWrap.width(navWidth);
					}else{
						$numberNavWrap.find("ul").width(navWidth);
					}
				}
				
				if(!isscreenshotgallery){
					if(jQuery.browser.safari){
						setTimeout(setnavWidth,200)
					}else{
						setnavWidth();
					}
				}
				//selected default code
				if(defaultSelected===true){
					jQuery("a",$numberNav).removeClass(options.activeClass);
					addclassSelector="a.progress:eq(" + (currPanel-1) + ")"
					jQuery(addclassSelector,$numberNav).addClass(options.activeClass);
					var leftstatic = ((currPanel-1)*panelWidth)*-1;
					if(isscreenshotgallery||ishighlights){
						var panheight=jQuery('div'+options.panelselector,$currSlider).eq(currPanel-1).outerHeight();
						jQuery('div.'+options.viewportClass,$currSlider).stop().animate({ height:panheight}, options.easeTime, options.easeFunc);
					}
					$panelContainer.css({left: leftstatic+'px'});
				}
				
				//rotator code
				if($currSlider.hasClass(options.rotateClass)){
					var rotateit = function(){
						if(currPanel==numPanels){
							currPanel=1;
						}else{
							currPanel++;
						}
						jQuery("a",$numberNav).removeClass(options.activeClass);
						addclassSelector="a.progress:eq(" + (currPanel-1) + ")";
						jQuery(addclassSelector,$numberNav).addClass(options.activeClass);
						movePanel(currPanel-1);
					}
					var rotateInterval = setInterval(rotateit,options.rotateSpeed);
					$currSlider.data("rotating",true);
					$currSlider.mouseover(function(){
						clearInterval(rotateInterval)
						$currSlider.data("rotating",false);
					});
				}

			});
			
		}	
	},MENTOR)
})();









