 $(document).ready(function() {
 
 // initialize
 	tp.init();
 
});

var tp = {

	// debug
	debug: function(message) {
		if (typeof(console) !== 'undefined' && console != null) console.log('[tp] ' + message);
	}

	// form section, back
	,formSectionBack: function() {
		// current section, total sections
		var section_selected = $('.form_basic .section').index($('.form_basic .section.section_selected'));
		// if the first section, do nothing
		if (section_selected == 0) return false;
		// else show the next section
		tp.formSectionShow(section_selected - 1);
	}

	// update form section controls
	,formSectionControlsUpdate: function() {
		// selected section, total number of sections, buttons
		var $pagination = $('.section_pagination')
			,section_selected = $('.form_basic .section').index($('.form_basic .section.section_selected'))
			,sections_total = $('.form_basic .section').length - 1
			,$button_back = $('.form_controls .back')
			,$button_next = $('.form_controls .next')
			,$button_submit = $('.form_controls .submit');
		// if first selected
		if (section_selected == 0) {
			// show next button
			$button_next.show();
			// hide back and submit
			$button_back.hide();
			$button_submit.hide();
		}
		// else if last selected
		else if (section_selected == sections_total) {
			// hide next button
			$button_next.hide();
			// show back and submit
			$button_back.show();
			$button_submit.show();
		}
		// else middle selected
		else {
			// show back and next
			$button_next.show();
			$button_back.show();
			// hide submit
			$button_submit.hide();
		}
		// update pagination
		$pagination.find('li').removeClass('selected').eq(section_selected).addClass('selected');
	}
	
	// form section pagination init
	,formSectionInit: function() {
		// write the nav for each of the sections
		var pagination_html = []
			$sections = $('.form_basic .section');
		pagination_html.push('<ul class="section_pagination">');
		$sections.each(function(index) {
			// write it
			pagination_html.push('	<li>' + (index + 1) + '</li>');
		});
		pagination_html.push('</ul>');
		$('#form_title').before('&nbsp;' + pagination_html.join('') + '&nbsp;');
		// back button
		$('.form_basic .back').click(function() {
			// show prev section
			tp.formSectionBack();
			// and stop
			return false;
		});
		// next button
		$('.form_basic .next').click(function () {
			// show next section
			tp.formSectionNext();
			// and stop
			return false;
		});
		// submit button
		$('.form_basic .submit').click(function() {
			// validate this section
			if (!tp.validateSection($('.form_basic .section.section_selected'))) return false;
			// and submit
			return true;
		});
		// initial form section control update
		tp.formSectionControlsUpdate();
	}

	// form section, next
	,formSectionNext: function() {
		// validate this section
		if (!tp.validateSection($('.form_basic .section.section_selected'))) return false;
		// current section, total sections
		var section_selected = $('.form_basic .section').index($('.form_basic .section.section_selected'))
			,sections_total = $('.form_basic .section').length - 1;
		// if the last section, do nothing
		if (section_selected == sections_total) return false;
		// else show the next section
		tp.formSectionShow(section_selected + 1);
	}
	
	// form section, show a section
	,formSectionShow: function(section_index) {
		// hide current section
		$('.form_basic .section.section_selected').removeClass('section_selected');
		// show new section
		$('.form_basic .section').eq(section_index).addClass('section_selected');
		// update section controls
		tp.formSectionControlsUpdate();
	}

	// init
	,init: function() {
		// form section pagination
		tp.formSectionInit();
		// recruiter form init
		tp.recruiterInit();
		// trigger list init
		tp.triggerListInit();
		// validator init
		tp.validateInit();
		 // setup ul.tabs to work as tabs for each div directly under div.panes
		$("ul.tabs").tabs(".panes > article", function() { $(".error").hide(); });
		$('.drivers_license_part').hide();
		$('#drivers_license_yes').click(function() { $('.drivers_license_part').show(); });
		$('#drivers_license_no').click(function() { $('.drivers_license_part').hide(); });
		$('.cdl_part').hide();
		$('#cdl_yes').click(function() { $('.cdl_part').show(); });
		$('#cdl_no').click(function() { $('.cdl_part').hide(); });
 		// noise background except for ie
		if (!$.browser.msie){
			$('body, #header .container_12, .box_bg, .student_img_hdr, .school_img_hdr, .exp_img_hdr').noisy({
			    intensity: 0.9,
			    size: 600,
			    opacity: 0.05,
			    fallback: '../img/noise.png',
			    monochrome: true
			});
		};
		// styled select (do this last as the trigger list stores a template of HTML for creating additional rows, and we dont want the styled HTML in the temp;ate)
		$('.input_select').StyledSelect();	
	}

	// recruiter form init
	,recruiterInit: function() {
		var $sections = $('.form_recruit');
		// submit button
		$('.form_recruit .submit').click(function() {
			// validate this section
			if (!tp.validateSection($('.form_recruit'))) return false;
			// and submit
			return true;
		});
	}

	// trigger list quantity controls update
	,triggerListQuantityControlsUpdate: function($trigger_list) {
		// is the list shown, number of rows, and the controls
		var list_shown = $trigger_list.find('.list li:visible').length
			,rows_total = $trigger_list.find('.list li').length
			,$controls = $trigger_list.find('.quantity_controls');
		// if list isn't shown hide controls
		if (!list_shown) $controls.hide();
		// else list is shown
		else {
			// show list
			$controls.show();
			// if only one row, hide remove button
			if (rows_total < 2) $controls.find('.remove').hide();
			// else show it
			else $controls.find('.remove').show();
		}
	}
	
	// trigger list's (if user selects 'yes' radio button, shows input field list, with addable/deletable rows)
	,triggerListInit: function() {
		// foreach trigger list
		$('.input_trigger_list').each(function() {
			// name of the list, write quantity nav html
			var list_name = $(this).attr('title')
				,nav_html = '<div class="quantity_controls"><a href="#" class="add">Add ' + list_name + '</a> <a href="#" class="remove">Remove ' + list_name + '</a></div>';
			// add in nav, remove title (for hover annoyance)
			$(this).append(nav_html).attr('title', '');
			// bind nav
			$(this).find('.quantity_controls .add').click(function() { tp.triggerListRowAdd($(this).parents('.input_trigger_list')); return false; });
			$(this).find('.quantity_controls .remove').click(function() { tp.triggerListRowRemove($(this).parents('.input_trigger_list')); return false; });
			// on trigger radio click
			$(this).find('.trigger input[type=radio]').click(function() {
				// if yes (positive number), show list items
				if (parseInt($(this).val())) tp.triggerListItemsShow($(this).parents('.input_trigger_list'));
				// else no, hide list items
				else tp.triggerListItemsHide($(this).parents('.input_trigger_list'));
			});
			// store a template of a list item
			$(this).data('tp_list_template', $(this).find('.list li').eq(0).outerHTML());
			// remove all the list items at the get go (this is because ie sucks and needs its hand held left and right)
			$(this).find('.list li').remove();
			// hide list items by default
			tp.triggerListItemsHide($(this));
			// update quantity nav
			tp.triggerListQuantityControlsUpdate($(this));
		});
	}
	
	
	// trigger list, hide list items
	,triggerListItemsHide: function($trigger_list) {
		// hide em
		$trigger_list.find('.list li').hide();
		// update quantity nav
		tp.triggerListQuantityControlsUpdate($trigger_list);
	}
	
	// trigger list, show list items
	,triggerListItemsShow: function($trigger_list) {
		// the list items
		var $list_items = $trigger_list.find('.list li');
		// show em
		$list_items.show();
		// if none of em, show at least one (again, this is for ie, rather than keeping just one in there)
		if (!$list_items.length) tp.triggerListRowAdd($trigger_list);
		// update quantity nav
		tp.triggerListQuantityControlsUpdate($trigger_list);
	}
	
	// trigger list, add a row
	,triggerListRowAdd: function($trigger_list) {
		// the number this row will be, and a rough template to pull from
		var row_number = $trigger_list.find('.list li').length
			,$row = $('<div>' + $trigger_list.data('tp_list_template') + '</div>');
		// update row inputs and select
		$row.find('input[type=text], select').each(function() {
			// new name & id
			var input_id = $(this).attr('id').replace(/[0-9]+/, row_number);
			// update name & id
			$(this).attr('id', input_id).attr('name', input_id);
		});
		// update row labels
		$row.find('label').each(function() {
			// update 'for' and text
			$(this).attr('for', $(this).attr('for').replace(/[0-9]+/, row_number)).text($(this).text().replace(/[0-9]+/, row_number+1));
		});
		// append to list and style the selects
		$trigger_list.find('.list').append($row.html()).find('.input_select').StyledSelect();
		// add validation to newly added HTML
		// tp.validateInit($trigger_list.find('li:last'));
		// update quantity nav
		tp.triggerListQuantityControlsUpdate($trigger_list);
	}
	
	// trigger list remove a row
	,triggerListRowRemove: function($trigger_list) {
		// remove the last list item
		$trigger_list.find('li:last').remove();
		// update quantity nav
		tp.triggerListQuantityControlsUpdate($trigger_list);
	}
	
	// ¡validator!
	,validate: function($field, type) {
		// define some shit
		var $label = $('label[for="' + $field.attr('id') + '"]') // the label
			,valid; // boolean field is valid
		// is valid?
		var valid = false;
		// validation type
		switch(type) {
			// date grou
			case 'date_group':
				// the parents
				var $date_group = $field.parents('.validate_date_group');
				// valid o tron
				var valid_month = $date_group.find('input[name*="month"], input[name*="Month"]').attr('value').length
					,has_day = $date_group.find('input[name*="day"], input[name*="Day"]').length
					,valid_day = has_day ? $date_group.find('input[name*="day"], input[name*="Day"]').attr('value').length : true
					,year_value = $date_group.find('input[name*="year"], input[name*="Year"]').eq(0).attr('value')
					,valid_year = year_value.length && (year_value > 1900) && (year_value <= new Date().getFullYear());
				valid = valid_month && valid_day && valid_year;
				// label
				$label = $date_group.find('.label');
				break;
			// email
			case 'email':
				// check against email pattern
				valid = $field.attr('value').match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
				break;
			// phone
			case 'phone':
				// check against phone pattern
				valid = $field.attr('value').match(/^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/);
				break;
			// postal code
			case 'postal_code':
				// check for us or canadian postal code
				valid = $field.attr('value').match(/[0-9]{5}(\-[0-9]{4})?/);
				break;
			// radio
			case 'radio':
				// check one of these clicked?
				valid = $('input[type="radio"][name="' + $field.attr('name') + '"]:checked').length;
				// custom label
				$label = $field.parents('.radio_group').siblings('.label');
				break;
			// styled select
			case 'styled_select_input':
				// the field value
				var value = $field.attr('value');
				// has value, with length
				valid = value && value.length;
				break;
			// text
			case 'text':
				// if has value
				valid = $field.attr('value').length;
				break;
		}
		// the validation status
		var $status = $label.siblings('.validation_status'); // the validation status
		// if no status yet, write one in
		if (!$status.length) var $status = $('<span class="validation_status"></span>').insertAfter($label);
		// if valid
		if (valid) {
			// update status and class
			$status.text('').removeClass('validation_status_error');
			// update field and field label
			$field.removeClass('input_error');
			$label.removeClass('label_error');
		}
		// else invalid
		else {
			// update status
			$status.text('!').addClass('validation_status_error');
			// update field and field label
			$field.addClass('input_error');
			$label.addClass('label_error');
		}
		// return if valid
		return valid;
	}
	
	// validator init
	,validateInit: function(context) {
		// add validator classes and event bindings
		$('.input_date_group', context).addClass('validate_date_group').find('.input_text').blur(function() { tp.validate($(this), 'date_group'); });
		$('.input_radio_group_required', context).addClass('validate_radio_group').find('input[type=radio]').click(function() { tp.validate($(this), 'radio'); });
		$('.input_text_email[required]', context).addClass('validate_email').blur(function() { tp.validate($(this), 'email'); });
		$('.input_text_phone[required]', context).addClass('validate_phone').blur(function() { tp.validate($(this), 'phone'); });
		$('.input_text_postal_code[required]', context).addClass('validate_postal_code').blur(function() { tp.validate($(this), 'postal_code'); });
		$('.input_text[required]', context).not('.input_text_email').not('.input_text_phone').not('.input_text_postal_code').addClass('validate_text').blur(function() { tp.validate($(this), 'text'); });
	}
	
	// on form submit
	,validateSection: function($section) {
		// final validation
		var field_count = 0
			,valid_count = 0;
		$section.find('.validate_date_group').each(function() {
			// ignore if hidden
			if ($(this).is(':hidden')) return;
			// else go for it
			field_count++;
			if (tp.validate($(this).find('.input_text').eq(0), 'date_group')) valid_count++;
		});
		$section.find('.validate_email').each(function() {
			// ignore if hidden
			if ($(this).is(':hidden')) return;
			// else go for it
			field_count++;
			if (tp.validate($(this), 'email')) valid_count++;
		});
		$section.find('.validate_phone').each(function() {
			// ignore if hidden
			if ($(this).is(':hidden')) return;
			// else go for it
			field_count++;
			if (tp.validate($(this), 'phone')) valid_count++;
		});
		$section.find('.validate_postal_code').each(function() {
			// ignore if hidden
			if ($(this).is(':hidden')) return;
			// else go for it
			field_count++;
			if (tp.validate($(this), 'postal_code')) valid_count++;
		});
		$section.find('.validate_radio_group').each(function() {
			// ignore if hidden
			if ($(this).is(':hidden')) return;
			// else go for it
			field_count++;
			if (tp.validate($(this).find('input[type=radio]').eq(0), 'radio')) valid_count++;
		});
		$section.find('.validate_text').each(function() {
			// ignore if hidden
			if ($(this).is(':hidden')) return;
			// else go for it
			field_count++;
			if (tp.validate($(this), 'text')) valid_count++;
		});
		$section.find('.styled_select_input').each(function() {
			// ignore if label is hidden
			if ($('label[for="' + $(this).attr('id') + '"]').is(':hidden')) return;
			// ignore if part of date group
			if ($(this).parents('.validate_date_group').length) return;
			// else go for it
			field_count++;
			if (tp.validate($(this), 'styled_select_input')) valid_count++;
		});
		// if not all valid
		if (valid_count != field_count) {
			// alert
			alert('Please correct the form errors.');
			// and stop
			return false;
		}
		// else submit it
		return true;
	}
};

/*
 
 jQuery Tools 1.2.5 Tabs- The basics of UI design.

 NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.

 http://flowplayer.org/tools/tabs/

 Since: November 2008
 Date:    Wed Sep 22 06:02:10 2010 +0000 
*/
(function(c){function p(d,b,a){var e=this,l=d.add(this),h=d.find(a.tabs),i=b.jquery?b:d.children(b),j;h.length||(h=d.children());i.length||(i=d.parent().find(b));i.length||(i=c(b));c.extend(this,{click:function(f,g){var k=h.eq(f);if(typeof f=="string"&&f.replace("#","")){k=h.filter("[href*="+f.replace("#","")+"]");f=Math.max(h.index(k),0)}if(a.rotate){var n=h.length-1;if(f<0)return e.click(n,g);if(f>n)return e.click(0,g)}if(!k.length){if(j>=0)return e;f=a.initialIndex;k=h.eq(f)}if(f===j)return e;
g=g||c.Event();g.type="onBeforeClick";l.trigger(g,[f]);if(!g.isDefaultPrevented()){o[a.effect].call(e,f,function(){g.type="onClick";l.trigger(g,[f])});j=f;h.removeClass(a.current);k.addClass(a.current);return e}},getConf:function(){return a},getTabs:function(){return h},getPanes:function(){return i},getCurrentPane:function(){return i.eq(j)},getCurrentTab:function(){return h.eq(j)},getIndex:function(){return j},next:function(){return e.click(j+1)},prev:function(){return e.click(j-1)},destroy:function(){h.unbind(a.event).removeClass(a.current);
i.find("a[href^=#]").unbind("click.T");return e}});c.each("onBeforeClick,onClick".split(","),function(f,g){c.isFunction(a[g])&&c(e).bind(g,a[g]);e[g]=function(k){k&&c(e).bind(g,k);return e}});if(a.history&&c.fn.history){c.tools.history.init(h);a.event="history"}h.each(function(f){c(this).bind(a.event,function(g){e.click(f,g);return g.preventDefault()})});i.find("a[href^=#]").bind("click.T",function(f){e.click(c(this).attr("href"),f)});if(location.hash&&a.tabs=="a"&&d.find("[href="+location.hash+"]").length)e.click(location.hash);
else if(a.initialIndex===0||a.initialIndex>0)e.click(a.initialIndex)}c.tools=c.tools||{version:"1.2.5"};c.tools.tabs={conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",rotate:false,history:false},addEffect:function(d,b){o[d]=b}};var o={"default":function(d,b){this.getPanes().hide().eq(d).show();b.call()},fade:function(d,b){var a=this.getConf(),e=a.fadeOutSpeed,l=this.getPanes();e?l.fadeOut(e):l.hide();l.eq(d).fadeIn(a.fadeInSpeed,b)},slide:function(d,
b){this.getPanes().slideUp(200);this.getPanes().eq(d).slideDown(400,b)},ajax:function(d,b){this.getPanes().eq(0).load(this.getTabs().eq(d).attr("href"),b)}},m;c.tools.tabs.addEffect("horizontal",function(d,b){m||(m=this.getPanes().eq(0).width());this.getCurrentPane().animate({width:0},function(){c(this).hide()});this.getPanes().eq(d).animate({width:m},function(){c(this).show();b.call()})});c.fn.tabs=function(d,b){var a=this.data("tabs");if(a){a.destroy();this.removeData("tabs")}if(c.isFunction(b))b=
{onBeforeClick:b};b=c.extend({},c.tools.tabs.conf,b);this.each(function(){a=new p(c(this),d,b);c(this).data("tabs",a)});return b.api?a:this}})(jQuery);


// OuterHTML v1.0.0 (Release version), http://www.darlesson.com/, jQuery outerHTML
(function($){$.fn.extend({outerHTML:function(value){if(typeof value==="string"){var $this=$(this),$parent=$this.parent();var replaceElements=function(){var $img=$this.find("img");if($img.length>0){$img.remove();}; var element;$(value).map(function(){element=$(this);$this.replaceWith(element);}); return element;}; return replaceElements();}else{return $("<div />").append($(this).clone()).html();}}});})(jQuery);




