jQuery( function($)
	{
	popup_init();
	print_init();
	accordion_init();
	video_init();
	siteSelector_init();
	estimate_init();
	formValidation();
	tabs_init();
	delete_action_init();
	progress_init();
	tooltip_init();
	} );


function accordion_init()
	{
	jQuery('dd:not(:first)').hide();
	jQuery('dt a').click( function()
		{
		jQuery('dd:visible').slideUp( 'slow' );
		jQuery(this).parent().next().slideDown( 'slow' );
		return false;
		} );
	}


function pop_up( Link )
	{
	var Url = Link.getAttribute( 'href' );
	var WindowName = Link.text; // or innerHTML
	var Window = window.open( Url, WindowName, 'menubar=yes, toolbar=no, location=no, status=yes, resizable=yes, scrollbars=yes, height=700, width=900' );
	if (window.focus)
		Window.focus();
	return true;
	}


var closure_pop_up = function( Link )
	{
	return function()
		{
		pop_up( Link );
		return false;
		}
	};


function popup_init()
	{
	var PopUps = jQuery( 'a.popup' );
	for (var i = 0; i < PopUps.length; i++)
		{
		PopUps[i].onclick = closure_pop_up( PopUps[i] );
		}
	}


function print_init()
	{
	jQuery( 'a.printable' ).click( function() { window.print(); return false } );
//	jQuery( '#PrintReport' ).each( function() { window.print(); } );
	}


function video_init()
	{
	jQuery( '#NoblisVideo' ).click( function()
		{
		showVideo();
		return false;
		} );
	}


function showVideo()
	{
	window.open( 'http://www.noblis.org/NoblisBrandVideo.htm?', '', 'scrollbars=no,menubar=no,height=340,width=420,resizable=yes,toolbar=no,location=no,status=no');
	}


function siteSelector_init()
	{
	jQuery( 'form.siteSelector input' ).click( function()
		{
		// Get the form.
		var F = jQuery(this.form);
		var inputs = [];
		// We probaby don't need all this escaping.
		jQuery(':input[@type=hidden]', F).each( function()
			{
			inputs.push( this.name + '=' + escape( this.value ) );
			} );
		inputs.push( this.name + '=' + escape( this.value ) );
		// Send the ajax query.
		jQuery.ajax( {
			url: F.attr('action'),
			data: inputs.join( '&' ),
			timeout: 3000,
			error: function()
				{
				console.log( 'failed to submit' );
				}
			} );
		} );
	}


function estimate_init()
	{
	jQuery('.estimate').click( function()
		{
		var Id = this.getAttribute( 'id' ).substring( 4 );
		var Value = this.getAttribute( 'name' );
		var Ans = document.getElementById( 'i_' + Id );
		Ans.setAttribute( 'value', Value );
		return false;
		} );
	}

/**
 * iterate over each input value
 * using onkeyup
 **/
function formValidation()
	{
	var errors = new Array();
	errors['not_empty'] = "Please enter a value.";
	errors['numbers'] = "Please enter numeric values only.";
	errors['letters'] = "Please enter letter values only.";
	errors['state'] = "Please enter a valid state.";
	errors['zip'] = "Please enter a valid zip code.";
	errors['alphanumeric'] = "Please enter alphanumeric values only.";
	errors['integer'] = "Please enter a valid integer value.";
	errors['year'] = "Please enter a valid year.";
	errors['pw'] = "Password does not meet criteria.";
	errors['confirmpw'] = "Passwords do not match.";
	errors['email'] = "Please enter a valid email address.";
	errors['website'] = "Please enter a valid web address.";
	errors['percentgroup'] = "Percents must total 100.";

	jQuery(":input").each( function(i) {
	if (jQuery(this).hasClass('not_empty'))
		{
			jQuery(this).keyup(function(e){
			if (validate_notempty(this.value))
				add_highlight(jQuery(this), errors['not_empty']);
			else
				remove_highlight(jQuery(this)); 		
			});
		}
	if (jQuery(this).hasClass('numbers'))
		{
			jQuery(this).keyup(function(e){
			if (validate_numbers(this.value))
				add_highlight(jQuery(this), errors['numbers']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('letters'))
		{
			jQuery(this).keyup(function(e){
			if (validate_letters(this.value))
				add_highlight(jQuery(this), errors['letters']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('state'))
		{
			jQuery(this).keyup(function(e){
			if (validate_state(this.value))
				add_highlight(jQuery(this), errors['state']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('zip'))
		{
			jQuery(this).keyup(function(e){
			if (validate_zip(this.value))
				add_highlight(jQuery(this), errors['zip']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('alphanumeric'))
		{
			jQuery(this).keyup(function(e){
			if (validate_alphanumeric(this.value))
				add_highlight(jQuery(this), errors['alphanumeric']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('integer'))
		{
			jQuery(this).keyup(function(e){
			if (validate_integer(this.value))
				add_highlight(jQuery(this), errors['integer']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('year'))
		{
			jQuery(this).keyup(function(e){
			if (validate_year(this.value))
				add_highlight(jQuery(this), errors['year']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('pw'))
		{
			jQuery(this).keyup(function(e){
			if (validate_pw(this.value))
				add_highlight(jQuery(this), errors['pw']);
			else
				remove_highlight(jQuery(this)); 	
			});
		}
	if (jQuery(this).hasClass('confirmpw'))
		{
			jQuery(this).keyup(function(e){
			if (validate_confirmpw(this.value))
				add_highlight(jQuery(this), errors['confirmpw']);
			else
				remove_highlight(jQuery(this)); 
			});
		}
	if (jQuery(this).hasClass('email'))
		{
			jQuery(this).keyup(function(e){
			if (validate_email(this.value))
				add_highlight(jQuery(this), errors['email']);
			else
				remove_highlight(jQuery(this)); 
			});
		}
	if (jQuery(this).hasClass('website'))
		{
			jQuery(this).keyup(function(e){
			if (validate_website(this.value))
				add_highlight(jQuery(this), errors['website']);
			else
				remove_highlight(jQuery(this)); 
			});
		}
		
	/**
	 * max_val: will always be used in conjunction with integer or numbers
	 * must test for both cases, and use the correct validation function
	 **/
	var max_val_index = jQuery(this).attr('class').indexOf('max_val:');
	if (max_val_index != -1)
		{
			var class_string = jQuery(this).attr('class');
			
			// the number will end with either a space (additional classes) or end of class name
			var index_space = class_string.indexOf(' ',max_val_index + 8);
			var index_length = class_string.length;
			
			// the length of the number x (max_val:x) will be either length to space, or length of class name (when index_space == -1)
			var end_index = 0;
			if ((index_space < index_length) && (index_space != -1))
			  	end_index = index_space;
			else
				end_index = index_length;
			
			var num_length = end_index - (max_val_index + 8);
			
			// thus the num can be determined with the substring
			var max_val_num = class_string.substring(max_val_index + 8, max_val_index + 8 + num_length);
			
			//alert('max_val_num = ' + max_val_num);
			
			jQuery(this).keyup(function(e){
			var max_val_result = validate_max_val(this.value, max_val_num);
			var test = false;
			var type = "";
			// if class also contains 'numbers'
			if (jQuery(this).attr('class').indexOf('numbers') != -1){
				test = (max_val_result || validate_numbers(this.value));
				word = "Numeric";
				}
			// if class also contains 'integer'
			else if (jQuery(this).attr('class').indexOf('integer') != -1){
				test = (max_val_result || validate_integer(this.value));
				word = "Integer";
				}
			if (test)
				add_highlight(jQuery(this), word + "  values up to " + max_val_num + " only.");
			else
				remove_highlight(jQuery(this));
			});
		}
	});

	/** 
	* validate all fields when submitting form
	* just in case a user clicks around a required field
	**/

	// percentage group object
	var percentgroup = {};
	
	jQuery( '.submitform' ).click (function ()
		{
		
		var sendForm = 1;

		// reset the percentgroup object first
		for (var i in percentgroup)
			percentgroup[i] = 0;
				
		jQuery(":input").each(function (i){
			if (jQuery(this).hasClass('not_empty'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['not_empty']);
					}
			}
			if (jQuery(this).hasClass('numbers'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['numbers']);
					}
			}
			if (jQuery(this).hasClass('letters'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['letters']);
					}
			}
			if (jQuery(this).hasClass('state'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['state']);
					}
			}
			if (jQuery(this).hasClass('zip'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['zip']);
					}
			}
			if (jQuery(this).hasClass('alphanumeric'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['alphanumeric']);
					}
			}
			if (jQuery(this).hasClass('integer'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['integer']);
					}
			}
			if (jQuery(this).hasClass('year'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['year']);
					}
			}
			if (jQuery(this).hasClass('pw'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['pw']);
					}
			}
			if (jQuery(this).hasClass('confirmpw'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['confirmpw']);
					}
			}
			if (jQuery(this).hasClass('email'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['email']);
					}
			}
			if (jQuery(this).hasClass('website'))
			{
				if (jQuery(this).hasClass('highlight') || (this.value == "")){
					sendForm = 0;
					add_highlight(jQuery(this), errors['website']);
					}
			}
			
			/**
			* Grab name of percent group
			**/
		var pg_index = jQuery(this).attr('class').indexOf('pg:');
		if (pg_index != -1)		
		{
			// obtain percent group letter name similar to max_value functionality above
			var class_string = jQuery(this).attr('class');		
			var index_space = class_string.indexOf(' ', pg_index + 3);
			var index_length = class_string.length;
			
			var end_index = 0;
			if ((index_space < index_length) && (index_space != -1))
			  	end_index = index_space;
			else
				end_index = index_length;	
			var num_length = end_index - (pg_index + 3);
			
			var pg_value = class_string.substring(pg_index + 3, pg_index + 3 + num_length);
			
			// check if pg_value(letter) is in the percentgroup object already; if it is, add the value of the input box to the array value.
			// if it's not already in the array, insert it.
			if (percentgroup.hasOwnProperty(pg_value))
				percentgroup[pg_value] += Number(this.value);
			else {
				percentgroup[pg_value] = Number(this.value);
			}		
			
		}	
	});
		// iterate the percentgroup object, based on the indices of the pgNames array. make sure corresponding percentages equal 100, and add highlights as necessary.
			for (var x in percentgroup)
			{
				if (percentgroup[x] != 100){
					sendForm = 0;
					jQuery("input[class*='pg:"+x+"']").each(function (i){
						add_highlight(jQuery(this), errors['percentgroup']);
					});
				}
				else {
					jQuery("input[class*='pg:"+x+"']").each(function (i){
						remove_highlight(jQuery(this));
					});
					sendForm = 1;
				}
			}

		if (sendForm == 0) {
			jQuery(this).next().html('Please fix all errors on page before submitting.');
			return false;
			}
		else {
			jQuery(this).next().html('');
			return true;
			}
		});
	}
	
/**
 * add class highlight and add the error message to the <span></span>
 * jq is the jquery object, error is the error msg
 **/
function add_highlight(jq, error)
	{
	jq.addClass('highlight');
	jq.next().html(error);
	}
	
/**
 * remove class highlight and remove error message from the <span></span>
 * jq is the jquery object
 **/
function remove_highlight(jq)
	{
	jq.removeClass('highlight');
	jq.next().html('');
	}

/**
 * validate an input field is not empty based on jQuery object, DOM value
 * if invalid, add 'highlight' class and error message.
 * otherwise, remove 'highlight' class and error message.
 * will be called on keyup AND on form submission.
 * each of the following functions (preceded by validate_) will follow this logic.
 **/ 
function validate_notempty(value)
	{
	return (value == "");
	}


/**
 * validate input field contains only numbers
 **/
function validate_numbers(value)
	{
	var regex = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
	return (!(regex.test(value)) || value == "");
	}
	

/**
 * validate input field contains only letters
 **/
function validate_letters(value)
	{
	var regex = /^[a-zA-Z ]+$/;
	return (!(regex.test(value)) || value == "");
	}


/** 
 * validate input field for state values
 **/
function validate_state(value)
	{
	var regex = /(^[A-Z]{2}$)/;
	return (!(regex.test(value)) || value == "");
	}


/**
 * validate input field for zip code
 **/
function validate_zip(value)
	{
	var regex = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
	return (!(regex.test(value)) || value == "");
	}


/**
 * validate input fields for alphanumeric characters
 **/
function validate_alphanumeric(value)
	{
	var regex = /^[\w ]+$/;
	return (!(regex.test(value)) || value == "");
	}


/**
 * validate input fields for integer values
 **/
function validate_integer(value)
	{
	var regex = /^\d+$/;
	return (!(regex.test(value)) || value == "");
	}


/**
 * validate baseline year values
 * must be between 1950 - 2050 (which was arbitrarily chosen)
 **/
function validate_year(value)
{
	var regex = /^((19|20)\d{2})$/;
	return (!(regex.test(value)) || ((value < 1950) || (value > 2050)) || value == "");			
}

/**--------------------------------------------------------------
 * validate password rules
 *
 * password checking:
 * the initial password field contains class:  .pw
 * confirm password field contains classes: .confirmpw
 *
 * .pw: regex's password requirements.
 * if its empty or if it fails, it returns an error "Password does not meet criteria"
 * and .highlight is applied. Once it passes, .highlight is removed.
 *
 * .confirmpw will not exist without .pw, therefore, if input.hasClass('.confirmpw'), 
 * (":input").('.pw') should return the first password field.
 *	.confirmpw validation will check only that .confirmpw.val() = .pw.val().
 *  if they aren't the same, add .highlight to .confirmpw, and add error to .confirmpw.span
 *  "Passwords do not match."
 * 
 * since an error exists, the page should not submit.
 *--------------------------------------------------------------
 **/
 
/**
 * validate that the password input meet password requirements
 * 1 uppercase, 1 lower, 1 digit, 1 symbol, 9-40 characters
 **/
function validate_pw(value)
	{
	var regex_metachar = /[@!#%&_:><\\\/\|\$\^\*\(\)\[\]\{\}\?\.\,\+]+/;
	var regex_az = /[a-z]{1,}/;
	var regex_AZ = /[A-Z]{1,}/;
	var regex_09 = /[\d]{1,}/;
	return (!(regex_metachar.test(value)) || !(regex_az.test(value)) || !(regex_AZ.test(value)) || !(regex_09.test(value)) ||((value.length < 9) || (value.length > 40)) || value== "");			
	}
	
	
/** 
* validate that .confirmpw matches .pw
* do not show error if both values are empty
**/
function validate_confirmpw(value)
	{
	var pw1 = jQuery('.pw').val();
	return ((pw1 != value) || (value == ""));		
	}


/** 
* validate email
* allow for _.-+
* regex via util.php
**/
function validate_email(value)
{
	var regex = /^([_a-z0-9\+-]+)(\.[_a-z0-9-\+]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
	return (!(regex.test(value)) || value == "");
}


/**
* validate URLs
* validation taken from util.php
**/
function validate_website(value)
{
	var regex = /^https?\:\/\/[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\/([a-z0-9+\$_-]\.?)+)*\/?$/;
	return (!(regex.test(value)) || value == "");
}


/**
 * take the max_value:x x for a number
 **/
function validate_max_val(value, num)
{
	return ((value > Number(num)) || (value < 0) || value == "");
}


function tabs_init()
	{
	// Normal tabs
	jQuery(".tabable > ul").tabs();

	// These tabs start out with any one selected as specified by
	// #tabable_current.  Also when the user clicks on these tabs, a new page
	// loads.
	jQuery(".tabable_getable > ul").tabs(
		{
		selected: parseInt(jQuery('.tabable_getable .current').html()),
		select: function(e, ui)
			{
			location.href = jQuery.data(ui.tab, 'load.tabs');
			return false;
		    }
		} );
	}


function delete_action_init()
	{
	jQuery( '.delete_action' ).click( function()
		{
		var Title = jQuery(this).attr("title");
		Msg = Title == undefined ? 'perform this action' : Title;
		return confirm('Are you sure you want to ' + Msg + '?');
		} );
	}


function number_format( number, decimals, dec_point, thousands_sep )
	{
	// http://kevin.vanzonneveld.net
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +     bugfix by: Michael White (http://crestidg.com)
	// +     bugfix by: Benjamin Lupton
	// +     bugfix by: Allan Jensen (http://www.winternet.no)
	// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +     bugfix by: Howard Yeend
	// *     example 1: number_format(1234.5678, 2, '.', '');
	// *     returns 1: 1234.57     

	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "." : dec_point;
	var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
	}


function progress_init()
	{
	jQuery( '.sg' ).hover
		(
		function ()
			{
			$(this).find( "img" ).css( "display", "block" );
			},
		function ()
			{
			$(this).find( "img" ).css( "display", "none" );
			}
		);
	}
	
/*
 * Tooltip script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
function tooltip_init(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$(".tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


	