if (! LR) { var LR = {}; }
if (! LR.config) { LR.config = {}; }

LR.addTokens = {};


if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
	jQuery(function($) {
	   $("a[rel='lightbox'], a[rel='lightbox[a]']").fancybox({
			padding: 10,
			showNavArrows : false
		});
	});
}
/* LIMIT TEXT AREA
--------------------------------- /*
	limit the word or character count of a specific textarea
	different words/characters are determined by the separator
	comma separation does not allow any spaces anywhere
	
	to limit by characters, use '' as the separator, and 
	count as the number of characters.
/* --------------------------------- */
function limit_textarea(form,area,count,separator)
{
	var textarea 	= eval('document.'+form+'.'+area);
	var text_value 	= textarea.value;
	var word_list	= text_value.split(separator);
	var word_count	= word_list.length;
	
	if(text_value != '')
	{
		// if the separator is a comma, the textarea's value should be a comma separated list
		if(separator == ',')
		{
			// if a space is found in the text...
			if(text_value.indexOf(' ') != -1)
			{
				// alert the user that spaces are not allowed
				alert('No spaces allowed, comma separated list');
				
				// remove everything upto and including the space
				textarea.value = textarea.value.substring(0,textarea.value.lastIndexOf(' '));
			}
		}
		if(word_count > count)
		{
			// alert that the limit has been reached/passed
			alert('You\'ve Reached Your Limit');
			
			// remove everything up to the last separator
			if(separator == '') textarea.value = textarea.value.substring(0,count);
			else textarea.value = textarea.value.substring(0,textarea.value.lastIndexOf(separator));
		}
	}
}





/* CREATE PROTECTED EMAIL
------------------------------------ /*
	- Takes the email address and creates a protected mailto link.
	- Prevents bots from harvesting email addresses.
	- Addresses must contain an '&' instead of the '@' symbol
	- Requires replacement text
	
/* ------------------------------------ */
function protect_email(addr,text)
{
	addr_top = addr.substr(0,addr.indexOf(':'));
	addr_btm = addr.substr(addr.indexOf(':')+1,addr.length);
	
	addr = "mai" + "lto" + ":" + addr_top + "@" + addr_btm;
	document.write('<a href="javascript:;" onMouseOver="javscript:this.href=\''+addr+'\';">'+text+'</a>');
}






/* CHECK/REMOVE HTTP://
------------------------------------ /*
	Checks the value for http:// and 
	removes it if found.
------------------------------------ */
function check_http(id,value)
{
	var return_value = value;
	if(value.indexOf('http://') != -1) return_value = value.substring(7,value.length);
	document.getElementById(id).value = return_value;
}






/* SELECT ALL INBOX MESSAGES
------------------------------------ /*
	Selects all inbox messages for removal
------------------------------------ */
function select_all(form,checked)
{
	var form 		= document.forms[form];
	var id_list 	= new Array();
		
	for(var i=0;i<form.length;i++)
	{
		var element = form[i];
		var type	= form[i].type;
		var name	= form[i].name;
		var id		= name.substring(4);
		
		if(checked && type == 'checkbox')
		{
			element.checked = true;
			if(id) id_list.push(id);
		}
		else if(!checked && type == 'checkbox')
		{
			element.checked = false;
			id_list = new Array();
		}
	}
	document.getElementById('rem_id_list').value = id_list.toString();
}






/* SELECT ONE INBOX MESSAGE
------------------------------------ /*
	Selects one inbox messages for removal
------------------------------------ */
function select_one(form)
{	
	var form 		= document.forms[form];	
	var id_list 	= new Array();

	for(var i=0;i<form.length;i++)
	{
		var element = form[i];
		var type	= form[i].type;
		var name	= form[i].name;
		var checked = form[i].checked;
		var id		= name.substring(4);		
		if(checked && type == 'checkbox')
		{
			if(id) id_list.push(id);
		}
	}
	document.getElementById('rem_id_list').value = id_list.toString();
}






/* CHANGES FORM ACTION
------------------------------------ /*
	this is used with image fields to initiate the cropping forms
	it is also used within the cropping forms, if there are multiple images needing to be cropped
	
	append the new action to url
/* ------------------------------------ */
function change_action(value,url,form_name)
{
   /*
	var form 			= $(form_name);
	var count 			= form.length;
	var new_action 		= url+'crop/';
		
	if(value != '') $(form_name).action = new_action;
	else $(form_name).action = url;*/
}





/* FORMAT NUMBER
------------------------------------ /*
	copyright Stephen Chapman 24th March 2006, 10th February 2007
	permission to use this function is granted provided
	that this copyright notice is retained intact
/* ------------------------------------ */
function formatNumber(number)
{
	var i = parseFloat(number);
	if(isNaN(i)) { i = 0.00; }
	var neg = '';
	if(i < 0) { neg = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = neg + s;
	return s;
}



/* ARRAY SUM
------------------------------------ /*
	adds all the values of a numeric array together
/* ------------------------------------ */
function sum (o){
    for(var s = 0, i = o.length; i; s += o[--i]);
    return s;
}








function writeCookie(name,value,days) {
	if (days==undefined) {
		days = 7;		// a week, if we don't specify
	}
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	if (name.split('.')[0]!='landscaperesource') { name = 'landscaperesource.'+name; }
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	if (name.split('.')[0]!='landscaperesource') { name = 'landscaperesource.'+name; }		
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
String.prototype.capitalize = function(){
   return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};






(function($){
	
	$.fn.extend({
		number: function() {
			$(this).each(function(){
				$(this).keyup(function(e){
					var charCode = e.keyCode;
					//console.log(charCode);
					if (charCode > 31 && (charCode < 48 || charCode > 57)) { 
						e.preventDefault();
						//console.log('false');
					}
				});
			});
			return this;
		},
		phone : function() {
		   $(this).each(function(){
		      
      		$(this).blur(function(e){
      			var val = $(this).val();
      			val = val.replace(new RegExp("[^0-9]", 'g'), '');
      			var phone = [];
      			if (val.substring(0,3)) { phone.push(val.substring(0,3)); }
      			if (val.substring(3,6)) { phone.push(val.substring(3,6)); }
      			if (val.substring(6)) { phone.push(val.substring(6)); }
      			val = phone.join('-');
      			$(this).val(val);
      		});

		   });
		   return this;
		}
	});
	
	function trace(msg) { 
		if (window['console'] && 0) { console.log(msg); }
	}
	LR.addTokens = function(params){
	   params.clas = (params.clas) ? params.clas : '.tokenize';
	   params.prePopulate = (params.prePopulate) ? params.prePopulate : [];
		$(params.clas).each(function(){
			var allowNewResult = ($(this).hasClass('allowNewResult')) ? true : false; 
			$(this).tokenInput(site_domain+'includes/ajax/autosuggest.php',{
			   prePopulate: params.prePopulate,
				minChars:2,
				queryParam:$(this).attr('name'),
				//preventDuplicates: true,
				tokenDelimiter: ',',
				//resultsFormatter: function(item){ var item_name = item.name; console.log(item_name); item_name = item_name.replace(/\\\&\#039\;/g,''); console.log(item_name); return "<li>"+ item_name + "</li>"; },
				//\&#039;
				allowNewResult : allowNewResult,
				tokenFormatter: function(item){ 
					return "<li><p>" + item.name + "</p></li>"; 
				},
				onAdd : function(){
					var id = $(this).attr('id');
					if (id) {
						var el = $('#token-input-'+id);
						if (el.length) {
							$(this).tokenInput('flush');
						}
					}
				},
				allowResizeInput: false


			});
		});
   }
	$(document).ready(function(){
	   
		$('img.autoscale').each(function(){
			
			trace('autoscale');
			var img = new Image();
			img.src = $(this).attr('src');

			if (img.height && img.width) {
				trace('there is image height and width');
				trace(img);
				trace(img.height);
				trace(img.width);
				if (img.height > img.width) {
					$(this).attr('width',$(this).attr('width')*(img.width / img.height));
				}
				
				if (img.height < img.width) {
					$(this).attr('height',$(this).attr('height')*(img.height / img.width));
				}
			}
		});
		
		$('.image a').imageResize();
		
		$('.rating').rating();
		
		$('.googleMap').googleMap();
		
		
		$('.cbx_toggle').checkboxToggle();
		
		
		// make long list info boxes be all clickable, not just the text
		$('.long_list .info_box').each(function(){
			$(this).click(function(){
				var a = $(this).find('a');
				window.location = $(a).attr('href');
			});
		});
		
		if ($('#remove_selected').length) {
			$('#remove_selected').parents('form').submit(function(e){
				var ids = [];
				$(this).find('input:checked').each(function(){
 					ids.push($(this).attr('name').split('_').pop());
				});
				$('#rem_id_list').val(ids.join(','));
			});
		}
		$('.number').number();
		
		
		
	});
	
	
	
	
	
	
	$.preloadImage = function(src,callback) {
		if (src) {
			return $('<img />')
			    .attr('src', src)
			    .load(function(){
					if (callback) { callback(); }
			    });
		} else {
			$('#homepage_features .loading').hide();
		}
	}
	
	$.fn.tagName = function() {
	    return this.get(0).tagName;
	}
	
	$.fn.rating = function() {
		$(this).each(function(){
			//console.log(this);
			var rel = $(this).attr('rel');
			if (rel) {
				var htmlString = '';
				for (var i = 0; i < rel; i++) {
					htmlString += '<div class="leaf"></div>';
				}
				for (var i = 0; i < 5 - rel; i++) {
					htmlString += '<div class="leaf_blur"></div>';
				}
				$(this).append(htmlString);
			} else {
				$(this).html('');
			}
		});
		return this;
	}
	
	$.fn.imageResize = function(keepSize) {

		$(this).each(function(){
			var image = $(this).find('img');
			if (image.length>0) {
				if (! keepSize) {
					/*
					imageWidth = image.width();
					imageHeight = image.height();

					// if image is less the size of its container, stretch it
					if (imageWidth > 0 && imageHeight > 0) {
						trace('image Resize, go');
						if (image.width()<$(this).parent().width()) {
							image.width($(this).parent().width());
						}
						if (image.height()<$(this).parent().height()) {
							image.height($(this).parent().height());
						}
						
						
						$(this).css({width:imageWidth,height:imageHeight}); // I don't think I need this

					}
					
					
					// does our image have width and height hard coded? throw them out.
					$(this).attr('width','');
					$(this).attr('height','');
					*/
				}
				
				

			}
		});
		return this;
	};
	
	
	$.fn.googleMap = function() {
		if (this.length>0) {		  	
			
			$(this).each(function(){
				
				var location = [];
				var ths = this;
				$(['address','city','state','zipcode']).each(function(){
					var content = $(ths).find('.'+this).html();
					if (content) { location.push(content); }
				});
				if (location.length) {
					location = location.join(', ');
					//console.log(location);

               var myOptions = {
                 zoom: 8,
                 mapTypeId: google.maps.MapTypeId.ROADMAP
               };
               
               
               var geocoder = new google.maps.Geocoder();

               
               var makeGoogleMap = function()
               {
                  map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
                  map.setCenter(myOptions.center);
                  var marker = new google.maps.Marker({
                        map: map,
                        position: myOptions.center
                  });
               }
               
               geocoder.geocode( { 'address': location}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {

                     
                     myOptions.center = results[0].geometry.location;
                     
                     if (map==null) {
                        makeGoogleMap();
                     }
                     
                     
                     $('#detailNavigation').detailTabs.addCallback('map',function(){
                        makeGoogleMap();
                     });
                     /*
                     if ($(ths).parent().parent() && $(ths).parent().detailTabs) {
                        $(ths).parent().detailTabs.addCallback()
                     }*/
                      
                  }
               });
               
               var map;               
               $('#detailNavigation').detailTabs.addCallback('map',function(){
                  if (myOptions.center) {
                     map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
                  }
                  //map.setCenter(results[0].geometry.location);
               });
					
				}
			});
		}
		return this;
	};
	
	$.fn.checkboxToggle = function() {
		$(this).each(function(i,ths){
			
			var target = $(ths).parent().next();
			if ($(this).attr('checked')) {
				$(target).show();
			}
			if (target.length>0) {
				$(ths).click(function(e){
					if ($(this).attr('checked')) {
						$(target).show();
					} else {
						$(target).hide();				
					}

				});
			}
		});
		return this;
	}
	
	$.fixLRLayout = function(forceAdd) {
		if (readCookie(window.location.pathname) || forceAdd) {
			$('#main_full').addClass('blank');
		}
		
	}	
	
})(jQuery);

var selectCurrentNavItem = function() {
	(function($){
		// figure out which element to highlight
		var path = window.location.pathname.substring(1).split('/').shift();
		var navElements = {
			'featured-landscapes' : 	'explore',
			'landscapes' : 				'explore',
			'landscape-elements' : 		'explore',
			'plants' : 					'learn',
			'plant-lists' : 			'learn',
			'plant-communities' : 		'learn',
			'maps' : 					'learn',
			'identify-your-eto-zone' : 	'learn',
			'water-usage' : 			'learn',
			'links' : 					'learn',
			'articles' : 				'learn',
			'about' : 					'learn',
			'palette-builder' : 		'share',
			'palette-lists' : 			'share',
			'blog' : 					'share',
			'our-contributors' : 		'share',
			'business-directory' : 		'connect',
			'events' : 					'connect',
			'contact' : 				'connect'
		};
		if (navElements[path]) {$('#nav-'+navElements[path]).addClass('slct');}
	})(jQuery);
}

var getThumb = function(image,size)
{
   image = image.split('.');
   
   size = parseInt(size);
   
	if (     size>LR.image_sizes.FULL)     { size=LR.image_sizes.FULL;}
	else if (size>LR.image_sizes.LARGE)    { size=LR.image_sizes.FULL;}
	else if (size>LR.image_sizes.MEDIUM)   { size=LR.image_sizes.LARGE;}
	else if (size>LR.image_sizes.SMALL)    { size=LR.image_sizes.MEDIUM;}
	else if (size>LR.image_sizes.MINI)     { size=LR.image_sizes.SMALL;}
	else                                   { size=LR.image_sizes.MINI;}
   
   
	return 'thumbs/'+image[0]+'-'+size+'.'+image[1];
}

LR.parseFileSize = function(fileSize)
{
   
	// Get the size of the file
	var fileSize = Math.round(fileSize / 1024);
	var suffix   = 'KB';				
	if (fileSize > 1000) {
		fileSize = Math.round(fileSize / 1000);
		suffix   = 'MB';
	}

	var fileSizeParts = fileSize.toString().split('.');
	fileSize = fileSizeParts[0];
	if (fileSizeParts.length > 1) {
		fileSize += '.' + fileSizeParts[1].substr(0,2);
	}

	fileSize += suffix;
	return fileSize;
}

LR.config.tooltip = {
	showDelay : 200,
	offsets : {x:10,y:-10}
};



Object.equals = function( x, y ) {
  if ( x === y ) return true;
    // if both x and y are null or undefined and exactly the same

  if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
    // if they are not strictly equal, they both need to be Objects

  if ( x.constructor !== y.constructor ) return false;
    // they must have the exact same prototype chain, the closest we can do is
    // test there constructor.

  for ( var p in x ) {
    if ( ! x.hasOwnProperty( p ) ) continue;
      // other properties were tested using x.constructor === y.constructor

    if ( ! y.hasOwnProperty( p ) ) return false;
      // allows to compare x[ p ] and y[ p ] when set to undefined

    if ( x[ p ] === y[ p ] ) continue;
      // if they have the same strict value or identity then they are equal

    if ( typeof( x[ p ] ) !== "object" ) return false;
      // Numbers, Strings, Functions, Booleans must be strictly equal

    if ( ! Object.equals( x[ p ],  y[ p ] ) ) return false;
      // Objects and Arrays must be tested recursively
  }

  for ( p in y ) {
    if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false;
      // allows x[ p ] to be set to undefined
  }
  return true;
}

function log(msg)
{
   if (window['console']) { console.log(msg); }
} ;window.onload = externalLinks;

function externalLinks()
{
	var objCurrent, objReplacement;

	if (document.getElementsByTagName)
	{
		var objAnchors = document.getElementsByTagName('a');
		for (var iCounter=0; iCounter<objAnchors.length; iCounter++)
		{
			if (objAnchors[iCounter].getAttribute('href') &&objAnchors[iCounter].getAttribute('rel') == 'external')
			{
				objAnchors[iCounter].onclick = function(event){return launchWindow(this, event);}
				objAnchors[iCounter].onkeypress = function(event){return launchWindow(this, event);}

				if (document.replaceChild)
				{
					objCurrent = objAnchors[iCounter].firstChild;
					if (objCurrent.nodeType == 3) // Text node
					{
						objReplacement = document.createTextNode(objCurrent.data);
						objAnchors[iCounter].replaceChild(objReplacement, objCurrent);
					}
					else if (objCurrent.alt) // Current element is an image
					{
						objReplacement = objCurrent;
						objReplacement.alt = objCurrent.alt + ' (opens in a new window)';
						
						try{objAnchors[iCounter].replaceChild(objReplacement, objCurrent);}
						catch(e){}
					}
				}
			}
		}
	}
}





function launchWindow(objAnchor, objEvent)
{
	var iKeyCode;

	if (objEvent && objEvent.type == 'keypress')
	{
		if (objEvent.keyCode) iKeyCode = objEvent.keyCode;
		else if (objEvent.which) iKeyCode = objEvent.which;
		if (iKeyCode != 13 && iKeyCode != 32) return true;
	}

	return !window.open(objAnchor);
} ;/* VALIDATE FORM (ONSUBMIT)
------------------------------------------------------------------- *
	checks all form elements passed in by required_fields.
	
	required_fields is an array set on every form page. It contains
	all the fields that need to be validated (does not use get element by id)
	
	First part makes sure the field isn't blank.
	Second, the 2 email fields are checked, field_1@field_2, no wierd characters
	Third, 
/* ------------------------------------------------------------------- */ 
function form_validate(form)
{
	var errors			= 0;
	var errorMessage	= '';
	var errorCallback	= null;
	var emailError 		= false;
	var blankError 		= false;
	var checkBoxGroups	= new Array();
	var checkBoxes		= new Array();
	var validBoxGroups	= new Array();
	var checkBoxParents	= new Array();
	
	if (! window.callbacks) { window.callbacks = {}; }
	
	
	//$$('input','select','textarea').each(function(e){
	jQuery(form).find('input, textarea, checkbox').each(function(e){
		// mixing jQuery and mootools; heavens me! feel free to improve this later -kscott
		var name	= e.get('name');
		var type	= e.get('type');
		var value	= e.get('value');
		var checked	= e.get('checked');
		var rel		= e.get('rel');		
		var array	= (e.name.indexOf('[]') != -1) ? true : false;
		var parent	= e.getParents('form').get('id');
		
		// we will deal with required checkbox arrays on their own.
		// to do that, we need to put them in an array for later
		// and skip them during regular checking
		if(parent == form && required_fields.contains(name) && type == 'checkbox'){
			checkBoxGroups.include(name);
			checkBoxParents.include(e.getParent('span'));
			checkBoxes.include(e);
		}
		
		
		if (! value && callbacks[name]) {
			errorCallback = callbacks[name];
		}
		
		// if this element is part of the form we are checking
		if(parent == form && required_fields.contains(name) && type != 'checkbox' && (callbacks && ! callbacks[name])   ){
			
			// if the field is blank then change to error style

			if(value == ''){
				errors++;
				toggleErrorDisplay(e,1);
				if(!blankError){
					errorMessage += 'Please make sure all enabled fields are filled in correctly.\n';
					blankError = true;
				}
			}
			// if the field is filled, then make sure the style is default
			else toggleErrorDisplay(e,0);
			
			
			// if this is an email field,
			if(blankError != true && name.indexOf('email') != -1){
				var atSym 		= value.indexOf('@');
				var lastAt 		= value.lastIndexOf('@');
				var dot			= value.indexOf('.');
				var lastDot		= value.lastIndexOf('.');
				var semiColon	= value.indexOf(';');
				var badChars 	= new Array(',',';',':','/','\\','&','#','!','$','%','*','<','>','?','\'','"');
				
				// verify that this is a good format (1 @ symbol in the middle, and a dot somewhere afterwards before the end)
				if( atSym == -1 || (atSym != lastAt) || !dot || (lastDot < atSym) || (lastDot == value.length-1) || semiColon != -1){
					errors++;
					errorMessage += 'Please check email address\n';
					emailError = true;
				}
				
				// check for any bad characters
				if(!emailError){
					badChars.each(function(e){
						if(value.indexOf(e) != -1){
							errors++;
							errorMessage += 'Email addresses cannot contain: "'+e+'"\n';
							emailError = true;
						}
					});
				}
				
				if(emailError) toggleErrorDisplay(e,1);
				else toggleErrorDisplay(e,0);
			}
		}
	});
	
	// check through the checkboxes
	// if at least one checkbox in each required group is checked,
	// then the form is ok/valid
	if(checkBoxes.length != 0){
		checkBoxes.each(function(e,i){
			// only search if there is something to be found
			// if a checkbox group has been validated,
			// skip the rest of the checkboxes
			if(!validBoxGroups.contains(name)){
				// the name is also the name of the group
				// this is what we will use to signify which groups
				// have been validated
				var name = e.get('name');
				var checked = e.get('checked');
				// if an item is checked, put it's name in the basket
				// this will indicate that the field is valid and
				// prevent any more boxes from being scanned
				if(checked) validBoxGroups.include(name);
			}
		});
		// confirm whether all required checkBoxGroups have
		// had at least one box checked
		if(validBoxGroups.length != checkBoxGroups.length){
			errors++;
			errorMessage += 'You must select at least one checkbox option from required checkbox field(s).\n';
			// now that we know which checkbox groups are valid and which aren't
			// we can change the background to illustrate which groups are required
			checkBoxGroups.each(function(e,i){
				// if the checkbox group is not available in the validBoxGroups array,
				// then the checkbox group was required, but not filled in.
				if(!validBoxGroups.contains(e)) toggleErrorDisplay(checkBoxParents[i],1);
				else toggleErrorDisplay(checkBoxParents[i],0);
			});
		}
		// if all checkbox groups are valid, then just make sure the user knows (ie: un-border the error areas)
		else checkBoxGroups.each(function(e,i){ toggleErrorDisplay(checkBoxParents[i],0); });
	}
	/* ------------------------ */
	
	
	if(errors){
		if (errorCallback) {
			errorCallback();
		} else {
			alert(errorMessage);
		}
		return false;
	}
	else {
		return true;
	} 
}

/* --- */

function toggleErrorDisplay(element,error){
	
	var eClass	= element.get('class');
	var eType	= element.get('type');
	var eTag	= element.get('tag');
	var eName	= element.get('name');
	
	var emptyClass	= (eClass == '');
	var isCheckbox	= (eType == 'checkbox');
	var isSelect	= (eTag == 'select');
	var isArray		= (eTag == 'span' && eClass == 'array');
	var isError		= (eClass == 'error');
	var hasError	= (eClass.indexOf('_error') != -1);
	
	if(error){
		// regular text fields
		if(emptyClass && !isCheckbox && !isSelect && !hasError && !isArray) element.set('class','error');
		// styled text fields
		else if(!emptyClass && !isCheckbox && !isSelect && !hasError && !isError && !isArray) element.set('class',eClass+'_error');
		// ?non? styled select fields
		else if(!emptyClass && !isCheckbox && isSelect && !hasError && !isError && !isArray) element.setStyle('border','solid 1px #D50');
		// for checkbox and radio button arrays
		else if(!emptyClass && !isCheckbox && !isSelect && !hasError && !isError && isArray) element.setStyle('border','solid 1px #D50');
		// for bare selects,* enable this if the ?non? one is causing funky stuff*
		//else if(!emptyClass && !isCheckbox && isSelect && !hasError && !isError && !isArray) element.setStyle('border','solid 1px #D50');
	}
	else{
		// regular text fields
		if(!emptyClass && !isCheckbox && !isSelect && isError && !isArray) element.erase('class');
		// styled text fields
		else if(!emptyClass && !isCheckbox && !isSelect && hasError && !isArray) element.set('class',eClass.replace('_error',''));
		// non styled select fields
		else if(!emptyClass && !isCheckbox && isSelect && !hasError && !isError && !isArray) element.setStyle('border','solid 1px #AAA');
		// for checkbox and radio button arrays
		else if(!emptyClass && !isCheckbox && !isSelect && !hasError && !isError && isArray) element.setStyle('border','none');
	}
}
/* ------------------------------------------------------------------- */






/* CONFIRM TEXT FIELD
------------------------------------------------------------------- *
	uses the id of the original field, and then determies the name of
	the confirm field. The confirm field name should be the name of the 
	original field, with a "confirm_" in front. "original_field" becomes 
	"confirm_original_field"
	
	if the fields do not match, an alert is sent out
/* ------------------------------------------------------------------- */
function confirm_textfield(id)
{
	/* get the original, and confirm field
	-------------------------------------- */
	var original_field 	= document.getElementById(id);
	var confirm_field 	= document.getElementById('confirm_'+id);
		
	/* let the user know
	-------------------------------------- */
	if(original_field.value != confirm_field.value) alert('Fields Do Not Match!');
}





/* --------------------------------------- /*
	checks to make sure that the value being
	entered is a valid number type. this also
	includes dashes, dots, parenthesis, and 
	the letters 'e','x', and 't' to allow
	the admin flexibility in how they layout
	the numbers.
	555-555-5555 vs. 555.555.5555 vs. (555) 555-5555
/* --------------------------------------- */
function checkNumberOnly(id)
{
	element 		= $(id);
	valid_chars		= '0123456789.,/-+()';
	
	for(i=0;i<element.value.length;i++)
	{
		ex_char = element.value.substring(i,i+1);
		if(valid_chars.indexOf(ex_char) == -1)
		{
			alert('Only Numbers Are Allowed Here!');		
			element.value = '';
			toggleErrorDisplay(element,true);
		}
		else toggleErrorDisplay(element,false);

	}
}





/* ------------------------------------- /*
	validates the length of the field, if
	there are supposed to be 5 numbers in 
	a zip code, this function will make 
	sure the user has entered 5.
/* ------------------------------------- */
function validate_length(id,length)
{
	var field_length = $(id).get('value').length;
	
	if(field_length < length)
	{
		alert('This field requires '+length+' characters MINIMUM');
		$(id).focus();
	}
} ;(function($){
	$(document).ready(function(){
		$('.image-gallery-widget').imageGallery();
	});
	
	// explicitly set the a's widths and heights to their contained images. this will allow us to center the images.
	$.fn.imageGallery = function() {

		var minHeight = 306;
		
		$(this).each(function(){

			var featuredWidget = $(this);
			if (featuredWidget.length>0) {
				
				var options = featuredWidget.attr('rel');

				var flipSpeed = 125;
				var fadeSpeed = 500;
				var imgs = []; // cache our preloaded image
				
				var displayImage = function(position) {
					var newImage = imgs[position].newImage;
					var caption = imgs[position].caption;
					newImageContainer = $('<a></a>').prepend(newImage);
					
					mainImage.prepend(newImageContainer);

					newImageContainer.hide().fadeIn(fadeSpeed);
					mainImage.find('.image').fadeOut(fadeSpeed,function(){ $(this).remove(); });
					
					caption = (caption) ? $('<div class="caption"><span>'+caption+'</span></div>') : $('');

					imageWidth = newImage.width();								
					imageHeight = newImage.height();
					mainImage.find('a:first').wrap('<div class="image"></div>').after(caption).next().css({margin: "0 0 0 -"+(imageWidth/2)+"px", width: imageWidth});

					mainImageHeight = (imageHeight > minHeight) ? imageHeight : minHeight;
					mainImage.animate({height: mainImageHeight});
				}
				
				var loadImage = function(thumbnail) {
					// ths refers to the thumbnail we are loading from

					// code for the thumbnail
					imageGallery.find('a').removeClass('slct');
					$(thumbnail).addClass('slct');
					imageGallery.find('a:not(.slct) img').fadeTo(flipSpeed,.2);
					$(thumbnail).find('img').fadeTo(flipSpeed,1);
					var position = $(thumbnail).attr('rel');
					var caption = $(thumbnail).find('img').attr('title');
					var thumbnailImage = $(thumbnail).find('img');
					// we want to determine whether we've already loaded this one or not
					if (imgs[position]) {
						displayImage(position);
					} else {

						if (thumbnailImage && thumbnailImage.attr('src')) { // then proceed with loading the main image
							var newImage = new Image();
							newImage.src = thumbnailImage.attr('src').replace(/\/thumbs/,'').replace(/-[0-9][0-9][0-9]./,'.');
							imgs[position] = {newImage:$(newImage),position:position,caption:caption,thumbnailImage:thumbnailImage};

							$(newImage).bind('load', function(){ displayImage(position);	});
						}
					}
					

				}

				var selectImage = function(e) {
					if (e&&e.preventDefault) { e.preventDefault(); }
					
					// set our 'ths' element; basically, get the thumbnail of which we're loading
					if ($(this).tagName()=='A') { var ths = this; }
					else if (e&&$(e).tagName()=='A') { var ths = e; }
					else { var ths = imageGallery.find('a:first'); }
					
					if (ths && ! ths.hasClass('slct')) { loadImage(ths); }
				}



				var imageGallery = featuredWidget.find('.image-gallery');
				var mainImage = featuredWidget.find('.main-image');
				if (mainImage.length==0) {
					mainImage = $('<div class="main-image"></div>');
					featuredWidget.prepend(mainImage);
				}

				//imageGallery.find('img').fadeTo(flipSpeed,.2);
				imageGallery.find('a').click(selectImage);
				selectImage();
				
				//make image Gallery scrollable, if necessary
				imageGalleryWidth = 0;
				
				imageGallery.find('a img').each(function(){
					imageGalleryWidth += $(this).width()+16;
				});
				
				if (imageGalleryWidth > imageGallery.width()) {
					imageGallery.css({height:'82px','overflowX':'auto'});
					imageGalleryContainer = imageGallery.find('.image-gallery-container');
					imageGalleryContainer.css('width',imageGalleryWidth);
				}
				
				featuredWidget.append('<a class="arrow_left arrow" href="javascript:;"></a><a class="arrow_right arrow" href="javascript:;"></a>')
				featuredWidget.find('.arrow').click(function(e){
					e.preventDefault();
					if ($(this).hasClass('arrow_left')) {
						var el = imageGallery.find('.slct').parent().prev();
						if (el.length==0) { el = imageGallery.find('.image:last'); }
					} else {
						var el = imageGallery.find('.slct').parent().next();
						if (el.length==0) { el = imageGallery.find('.image:first'); }
					}
					selectImage($(el).find('a'));
				});
				
				//imageGallery.hide();
			}
		});
		return this;
	}
	
})(jQuery); ;(function($){
	$.fn.extend({
		recentActivity : function(){
			$(this).each(function(){
				var recentActivity = $(this);
				if (recentActivity.length>0) {
					var recentActivityCalculator = function() {
						recentActivity.find('.meta').each(function(i,el){
							var theDate = prettyDate($(this).attr('rel'));
							$(this).html(theDate);
						});
					};
					var recentActivityTimer = setInterval(function(){
						recentActivityCalculator();
					},1000*60);
					recentActivityCalculator();
				}
			});
			return this;
		}
	})
	$(document).ready(function(){
		$('#recent-activity').recentActivity();
		$('#activity_list').recentActivity();
	});
	
	
	/*
	 * JavaScript Pretty Date
	 * Copyright (c) 2008 John Resig (jquery.com)
	 * Licensed under the MIT license.
	 */

	// Takes an ISO time and returns a string representing how
	// long ago the date represents.
	function prettyDate(time){
		var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
			diff = (((new Date()).getTime() - date.getTime()) / 1000),
			day_diff = Math.floor(diff / 86400);
		if ( isNaN(day_diff) || day_diff < 0 )
			return;

		return day_diff == 0 && (
				diff < 60 && "just now" ||
				diff < 120 && "1 minute ago" ||
				diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
				diff < 7200 && "1 hour ago" ||
				diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
			day_diff == 1 && "Yesterday" ||
			day_diff < 7 && day_diff + " days ago" ||
			day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
			(date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
	}
	
})(jQuery); ;(function($){
	$(document).ready(function(){
		
		var climateDataStateCookie = readCookie('climateDataStateCookie');
		var climateDataState = (climateDataStateCookie) ? climateDataStateCookie : 1;
		var imgs, climateDataStatus, climateData, stationInfo, climateDataA;
		var zipcodeSelector;
		
		var toggleClimateData = function() {
			// if our cookie is set to 0, we show it.
			if (parseInt(climateDataState)) {					// when our state is set to 1, we hide it (and state becomes 0)
				climateData.addClass('collapsed');
				climateDataState = 0;
				climateDataStatus.html('(Show Data)');
				$(imgs[1]).hide();
				stationInfo.hide();

			} else {								// when our state is currently 0, we show it (and state becomes 1)
				climateDataState = 1;
				climateDataStatus.html('(Hide Data)');
				$(imgs[1]).show();
				stationInfo.show();							
				climateData.removeClass('collapsed');

			}
			writeCookie('climateDataStateCookie',((((climateDataState*2)-1)*-1)+1)/2,30);
		}

		var newStations, stationName, newStationSelector;
		var stationPage = 0;
		
		var pickNewStation = function(e) {
			var li = $(this).parent();
			var stationID = li.attr('id').split('-').pop();
			var stationNameVal = li.attr('rel');
			$.get('/includes/ajax/station_picker.php',{station_id:stationID},function(data){
				if (data) {
					stationPage = 0;
					$('#station-information').html(data);
					setHandlers();
				}
			});
			
		};
		var selectNewStation = function(e) {
			e.preventDefault();
			newStations.show();
			$.get('/includes/ajax/station_picker.php',{page:stationPage},function(data){
				data = $.parseJSON(data);
				stationPage++;
				var stationHtml = '';
				var currentStationID = stationName.attr('rel');
				var checked = null;
				$(data).each(function(){
					if (currentStationID==this.station_id) { checked = ' checked="checked" '; }
					else { checked = null; }
					stationHtml += '<li id="station-'+this.station_id+'" rel="'+this.station_name+'"><input name="station-pick" class="station-pick" type="radio" '+checked+'/>'+this.station_name.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()})+' ('+this.distance+' miles away)</li>';
				})
				newStations.append(stationHtml);
				newStationSelector.html('More stations...');
				$('.station-pick').unbind('click').click(pickNewStation);
			});
		};
		var toggleZipcodeSelector = function(e) {
			e.preventDefault();
			if (zipcodeSelector.is(':visible')) { zipcodeSelector.hide(); }
			else { zipcodeSelector.show(); }
		}
		
		var setHandlers = function() {
			stationName = $('#station-name');
			newStations = $('#new-stations');
			imgs = $('#climate-data img');	
			climateDataStatus = $('#climate-data-status');	
			climateData = $('#climate-data');
			climateDataA = $('#climate-data a');
			stationInfo = $('#station-info');
			newStationSelector = $('#select-new-station');
			updateZipcodeSelector = $('#update-zipcode-reveal');
			zipcodeSelector = $('#localize-it');
			
			climateDataA.click(toggleClimateData);
			newStationSelector.click(selectNewStation);
			updateZipcodeSelector.click(toggleZipcodeSelector);
		}
		setHandlers();
		toggleClimateData();
	});	
	
})(jQuery); ;(function($) {
	var has_VML, create_canvas_for, add_shape_to, clear_canvas, shape_from_area,
		canvas_style, fader, hex_to_decimal, css3color, is_image_loaded, options_from_area;

	has_VML = document.namespaces;
	has_canvas = !!document.createElement('canvas').getContext;

	if(!(has_canvas || has_VML)) {
		$.fn.maphilight = function() { return this; };
		return;
	}
	
	if(has_canvas) {
		fader = function(element, opacity, interval) {
			if(opacity <= 1) {
				element.style.opacity = opacity;
				window.setTimeout(fader, 10, element, opacity + 0.1, 10);
			}
		};
		
		hex_to_decimal = function(hex) {
			return Math.max(0, Math.min(parseInt(hex, 16), 255));
		};
		css3color = function(color, opacity) {
			return 'rgba('+hex_to_decimal(color.substr(0,2))+','+hex_to_decimal(color.substr(2,2))+','+hex_to_decimal(color.substr(4,2))+','+opacity+')';
		};
		create_canvas_for = function(img) {
			var c = $('<canvas style="width:'+img.width+'px;height:'+img.height+'px;"></canvas>').get(0);
			c.getContext("2d").clearRect(0, 0, c.width, c.height);
			return c;
		};
		add_shape_to = function(canvas, shape, coords, options, name) {
			var i, context = canvas.getContext('2d');
			context.beginPath();
			if(shape == 'rect') {
				context.rect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
			} else if(shape == 'poly') {
				context.moveTo(coords[0], coords[1]);
				for(i=2; i < coords.length; i+=2) {
					context.lineTo(coords[i], coords[i+1]);
				}
			} else if(shape == 'circ') {
				context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, false);
			}
			context.closePath();
			if(options.fill) {
				context.fillStyle = css3color(options.fillColor, options.fillOpacity);
				context.fill();
			}
			if(options.stroke) {
				context.strokeStyle = css3color(options.strokeColor, options.strokeOpacity);
				context.lineWidth = options.strokeWidth;
				context.stroke();
			}
			if(options.fade) {
				fader(canvas, 0);
			}
		};
		clear_canvas = function(canvas) {
			canvas.getContext('2d').clearRect(0, 0, canvas.width,canvas.height);
		};
	} else {   // ie executes this code
		create_canvas_for = function(img) {
			return $('<var style="zoom:1;overflow:hidden;display:block;width:'+img.width+'px;height:'+img.height+'px;"></var>').get(0);
		};
		add_shape_to = function(canvas, shape, coords, options, name) {
			var fill, stroke, opacity, e;
			fill = '<v:fill color="#'+options.fillColor+'" opacity="'+(options.fill ? options.fillOpacity : 0)+'" />';
			stroke = (options.stroke ? 'strokeweight="'+options.strokeWidth+'" stroked="t" strokecolor="#'+options.strokeColor+'"' : 'stroked="f"');
			opacity = '<v:stroke opacity="'+options.strokeOpacity+'"/>';
			if(shape == 'rect') {
				e = $('<v:rect name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+coords[0]+'px;top:'+coords[1]+'px;width:'+(coords[2] - coords[0])+'px;height:'+(coords[3] - coords[1])+'px;"></v:rect>');
			} else if(shape == 'poly') {
				e = $('<v:shape name="'+name+'" filled="t" '+stroke+' coordorigin="0,0" coordsize="'+canvas.width+','+canvas.height+'" path="m '+coords[0]+','+coords[1]+' l '+coords.join(',')+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+canvas.width+'px;height:'+canvas.height+'px;"></v:shape>');
			} else if(shape == 'circ') {
				e = $('<v:oval name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(coords[0] - coords[2])+'px;top:'+(coords[1] - coords[2])+'px;width:'+(coords[2]*2)+'px;height:'+(coords[2]*2)+'px;"></v:oval>');
			}
			e.get(0).innerHTML = fill+opacity;
			$(canvas).append(e);
		};
		clear_canvas = function(canvas) {
			$(canvas).find('[name=highlighted]').remove();
		};
	}
	
	shape_from_area = function(area) {
		var i, coords = area.getAttribute('coords').split(',');
		for (i=0; i < coords.length; i++) { coords[i] = parseFloat(coords[i]); }
		return [area.getAttribute('shape').toLowerCase().substr(0,4), coords];
	};

	options_from_area = function(area, options) {
		var $area = $(area);
		return $.extend({}, options, $.metadata ? $area.metadata() : false, $area.data('maphilight'));
	};
	
	is_image_loaded = function(img) {
		if(!img.complete) { return false; } // IE
		if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { return false; } // Others
		return true;
	};

	canvas_style = {
		position: 'absolute',
		left: 0,
		top: 0,
		padding: 0,
		border: 0
	};
	
	var ie_hax_done = false;
	$.fn.maphilight = function(opts) {
		opts = $.extend({}, $.fn.maphilight.defaults, opts);
		
		if($.browser.msie && !ie_hax_done) {
			document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
			var style = document.createStyleSheet();
			var shapes = ['shape','rect', 'oval', 'circ', 'fill', 'stroke', 'imagedata', 'group','textbox'];
			$.each(shapes,
				function() {
					style.addRule('v\\:' + this, "behavior: url(#default#VML); antialias:true");
				}
			);
			ie_hax_done = true;
		}
		
		return this.each(function() {
			var img, wrap, options, map, canvas, canvas_always, canvas_clicked, mouseover, highlighted_shape, usemap;
			img = $(this);

			if(!is_image_loaded(this)) {
				// If the image isn't fully loaded, this won't work right.  Try again later.
				return window.setTimeout(function() {
					img.maphilight(opts);
				}, 200);
			}

			options = $.extend({}, opts, $.metadata ? img.metadata() : false, img.data('maphilight'));

			// jQuery bug with Opera, results in full-url#usemap being returned from jQuery's attr.
			// So use raw getAttribute instead.
			usemap = img.get(0).getAttribute('usemap');

			map = $('map[name="'+usemap.substr(1)+'"]');

			if(!(img.is('img') && usemap && map.size() > 0)) { return; }

			if(img.hasClass('maphilighted')) {
				// We're redrawing an old map, probably to pick up changes to the options.
				// Just clear out all the old stuff.
				var wrapper = img.parent();
				img.insertBefore(wrapper);
				wrapper.remove();
				$(map).unbind('.maphilight').find('area[coords]').unbind('.maphilight');
			}

			wrap = $('<div></div>').css({
				display:'block',
				background:'url('+this.src+')',
				position:'relative',
				padding:0,
				width:this.width,
				height:this.height
				});
			if(options.wrapClass) {
				if(options.wrapClass === true) {
					wrap.addClass($(this).attr('class'));
				} else {
					wrap.addClass(options.wrapClass);
				}
			}
			img.before(wrap).css('opacity', 0).css(canvas_style).remove();
			if($.browser.msie) { img.css('filter', 'Alpha(opacity=0)'); }
			wrap.append(img);
			
			canvas = create_canvas_for(this);
			$(canvas).css(canvas_style);
			canvas.height = this.height;
			canvas.width = this.width;
			
			mouseover = function(e) {
				var shape, area_options;
				area_options = options_from_area(this, options);
				if(
					!area_options.neverOn
					&&
					!area_options.alwaysOn
				) {
					
					/***** Check: if we are leaving hover states after click, we don't want double fades *****/
					if (! area_options.stayClicked || ! $(this).hasClass('selected')) {
						shape = shape_from_area(this);
						add_shape_to(canvas, shape[0], shape[1], area_options, "highlighted");
						if(area_options.groupBy && $(this).attr(area_options.groupBy)) {
							var first = this;
							map.find('area['+area_options.groupBy+'='+$(this).attr(area_options.groupBy)+']').each(function() {
								if(this != first) {
									var subarea_options = options_from_area(this, options);
									if(!subarea_options.neverOn && !subarea_options.alwaysOn) {
										var shape = shape_from_area(this);
										add_shape_to(canvas, shape[0], shape[1], subarea_options, "highlighted");
									}
								}
							});
						}
					}
					
				}
			}
			/***** New click code *****/
			click = function(e){ 
				
				if(canvas_clicked) {
					$(map).find('.selected').removeClass('selected');
					clear_canvas(canvas_clicked);
					clear_canvas(canvas);
				}
				$(this).addClass('selected');						
				if(!has_canvas) {
					$(canvas).empty();
				}
				$(map).find('.selected').each(function() {
					var shape, area_options;
					area_options = options_from_area(this, options);
					if(area_options.stayClicked) {
						if (has_canvas) {

							if(!canvas_clicked) {
								canvas_clicked = create_canvas_for(img.get());
								$(canvas_clicked).css(canvas_style);
								canvas_clicked.width = img.width();
								canvas_clicked.height = img.height();
								img.before(canvas_clicked);
							}
							shape = shape_from_area(this);
							add_shape_to(canvas_clicked, shape[0], shape[1], area_options, "");
						}
					}
				});
			}

			$(map).bind('alwaysOn.maphilight', function() {
				// Check for areas with alwaysOn set. These are added to a *second* canvas,
				// which will get around flickering during fading.
				if(canvas_always) {
					clear_canvas(canvas_always)
				}
				if(!has_canvas) {
					$(canvas).empty();
				}
				$(map).find('area[coords]').each(function() {
					var shape, area_options;
					area_options = options_from_area(this, options);
					if(area_options.alwaysOn) {
						if(!canvas_always && has_canvas) {
							canvas_always = create_canvas_for(img.get());
							$(canvas_always).css(canvas_style);
							canvas_always.width = img.width();
							canvas_always.height = img.height();
							img.before(canvas_always);
						}
						shape = shape_from_area(this);
						if (has_canvas) {
							add_shape_to(canvas_always, shape[0], shape[1], area_options, "");
						} else {
							add_shape_to(canvas, shape[0], shape[1], area_options, "");
						}
					}
				});
			});
			
			if(options.alwaysOn) {
				$(map).find('area[coords]').each(mouseover);
			} else {
				$(map).find('area[coords]')
					.trigger('alwaysOn.maphilight')
					.bind('mouseover.maphilight', mouseover)
					.bind('mouseout.maphilight', function(e) { clear_canvas(canvas); })
					.bind('click.maphilight', click)
					;
			}
			
			img.before(canvas); // if we put this after, the mouseover events wouldn't fire.
			
			img.addClass('maphilighted');
		});
	};
	$.fn.maphilight.defaults = {
		fill: true,
		fillColor: '000000',
		fillOpacity: 0.2,
		stroke: true,
		strokeColor: 'ff0000',
		strokeOpacity: 1,
		strokeWidth: 1,
		fade: true,
		alwaysOn: false,
		neverOn: false,
		groupBy: false,
		wrapClass: true
	};
})(jQuery); ;Encoder = {

	// When encoding do we convert characters into html or numerical entities
	EncodeType : "entity",  // entity OR numerical

	isEmpty : function(val){
		if(val){
			return ((val===null) || val.length==0 || /^\s+$/.test(val));
		}else{
			return true;
		}
	},
	// Convert HTML entities into numerical entities
	HTML2Numerical : function(s){
		var arr1 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&Oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		var arr2 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		return this.swapArrayVals(s,arr1,arr2);
	},	

	// Convert Numerical entities into HTML entities
	NumericalToHTML : function(s){
		var arr1 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		var arr2 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&Oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		return this.swapArrayVals(s,arr1,arr2);
	},


	// Numerically encodes all unicode characters
	numEncode : function(s){
		
		if(this.isEmpty(s)) return "";

		var e = "";
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (c < " " || c > "~")
			{
				c = "&#" + c.charCodeAt() + ";";
			}
			e += c;
		}
		return e;
	},
	
	// HTML Decode numerical and HTML entities back to original values
	htmlDecode : function(s){

		var c,m,d = s;
		
		if(this.isEmpty(d)) return "";

		// convert HTML entites back to numerical entites first
		d = this.HTML2Numerical(d);
		
		// look for numerical entities &#34;
		arr=d.match(/&#[0-9]{1,5};/g);
		
		// if no matches found in string then skip
		if(arr!=null){
			for(var x=0;x<arr.length;x++){
				m = arr[x];
				c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
				// if its a valid number we can decode
				if(c >= -32768 && c <= 65535){
					// decode every single match within string
					d = d.replace(m, String.fromCharCode(c));
				}else{
					d = d.replace(m, ""); //invalid so replace with nada
				}
			}			
		}

		return d;
	},		

	// encode an input string into either numerical or HTML entities
	htmlEncode : function(s,dbl){
			
		if(this.isEmpty(s)) return "";

		// do we allow double encoding? E.g will &amp; be turned into &amp;amp;
		dbl = dbl | false; //default to prevent double encoding
		
		// if allowing double encoding we do ampersands first
		if(dbl){
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}
		}

		// convert the xss chars to numerical entities ' " < >
		s = this.XSSEncode(s,false);
		
		if(this.EncodeType=="numerical" || !dbl){
			// Now call function that will convert any HTML entities to numerical codes
			s = this.HTML2Numerical(s);
		}

		// Now encode all chars above 127 e.g unicode
		s = this.numEncode(s);

		// now we know anything that needs to be encoded has been converted to numerical entities we
		// can encode any ampersands & that are not part of encoded entities
		// to handle the fact that I need to do a negative check and handle multiple ampersands &&&
		// I am going to use a placeholder

		// if we don't want double encoded entities we ignore the & in existing entities
		if(!dbl){
			s = s.replace(/&#/g,"##AMPHASH##");
		
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}

			s = s.replace(/##AMPHASH##/g,"&#");
		}
		
		// replace any malformed entities
		s = s.replace(/&#\d*([^\d;]|$)/g, "$1");

		if(!dbl){
			// safety check to correct any double encoded &amp;
			s = this.correctEncoding(s);
		}

		// now do we need to convert our numerical encoded string into entities
		if(this.EncodeType=="entity"){
			s = this.NumericalToHTML(s);
		}

		return s;					
	},

	// Encodes the basic 4 characters used to malform HTML in XSS hacks
	XSSEncode : function(s,en){
		if(!this.isEmpty(s)){
			en = en || true;
			// do we convert to numerical or html entity?
			if(en){
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&quot;");
				s = s.replace(/</g,"&lt;");
				s = s.replace(/>/g,"&gt;");
			}else{
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&#34;");
				s = s.replace(/</g,"&#60;");
				s = s.replace(/>/g,"&#62;");
			}
			return s;
		}else{
			return "";
		}
	},

	// returns true if a string contains html or numerical encoded entities
	hasEncoded : function(s){
		if(/&#[0-9]{1,5};/g.test(s)){
			return true;
		}else if(/&[A-Z]{2,6};/gi.test(s)){
			return true;
		}else{
			return false;
		}
	},

	// will remove any unicode characters
	stripUnicode : function(s){
		return s.replace(/[^\x20-\x7E]/g,"");
		
	},

	// corrects any double encoded &amp; entities e.g &amp;amp;
	correctEncoding : function(s){
		return s.replace(/(&amp;)(amp;)+/,"$1");
	},


	// Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
	swapArrayVals : function(s,arr1,arr2){
		if(this.isEmpty(s)) return "";
		var re;
		if(arr1 && arr2){
			//ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
			// array lengths must match
			if(arr1.length == arr2.length){
				for(var x=0,i=arr1.length;x<i;x++){
					re = new RegExp(arr1[x], 'g');
					s = s.replace(re,arr2[x]); //swap arr1 item with matching item from arr2	
				}
			}
		}
		return s;
	},

	inArray : function( item, arr ) {
		for ( var i = 0, x = arr.length; i < x; i++ ){
			if ( arr[i] === item ){
				return i;
			}
		}
		return -1;
	}

};

 ;var writeDummyData = function(ini_val) {
	var path = window.location.pathname.split('/')[1];
			console.log(required_fields);
			console.log(path);
	if (
		path=='register'||
		path=='register-business' ||
		path=='sign-up' 
	)
	{
		(function($){
			var prepend = 'dummyData_';

			for (var i = 0; i < required_fields.length; i++) {
				var field = required_fields[i];
				var input = $('input[name='+field+']');

				if (! input.length) {
					input = $('select[name='+field+']');
				}
								
				var type = $(input).attr('type');
				console.log(type);
				switch(type) {
					case 'checkbox' :
						input.attr('checked','checked');
					break;
					
					case 'text' :
                  console.log('text');
						switch(field) {
							case 'screen_name' :
								if (ini_val) {
									var val = ini_val;
								} else {
									var val = prepend+Math.round(Math.random(0,1)*1000);
								}
							break;
							case 'email' : case 'business_email' :
								if (ini_val) {
									var val = ini_val+'@scottlabsllc.com';
								} else {
									var val = prepend+Math.round(Math.random(0,1)*1000)+'@scottlabsllc.com';
								}
							break;
							case 'zipcode' :
								var val = '90210';
							break;
							case 'recaptcha_response_field' :
								var val = '';
							break;
							default :
								var val = prepend+Math.round(Math.random(0,1)*1000);
							break;

						}
						console.log(input);
						console.log(val);

						input.val(val);
					break;
					case 'password' :
						input.val('12345');
					break;
					default : // its a select, or textarea
						input.val('1');
					break;
				}
			};
			
		})(jQuery);
	}
} ;
