/*  File: basic.js          */
/*  Ver:  2011-02-01        */

/********************************
  the following routines require 
    jquery.js
*********************************/

// extend browser object to define IE6
$.browser.msie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent);

// extend browser object to define IE7
$.browser.msie7 = $.browser.msie && /MSIE 7\.0/i.test(window.navigator.userAgent);


// extend jquery with synchronize height function
(function($){$.fn.syncHeight=function(settings){var max=0;var browser_id=0;var property=[['min-height','0px'],['height','1%']];if($.browser.msie&&$.browser.version<7){browser_id=1;}
$(this).each(function(){$(this).css(property[browser_id][0],property[browser_id][1]);var val=$(this).height();if(val>max){max=val;}});$(this).each(function(){$(this).css(property[browser_id][0],max+'px');});return this;};})(jQuery);


// extend jquery with column list function
jQuery.fn.make_column_list = function(settings){
	settings = jQuery.extend({
		colWidth: new Array(220,220) // set column width(s)
	}, settings);

	if (jQuery('> li', this))
	{
		this.each(function(y) {
			var y = jQuery('.li_container').size(),
				col_Width = settings.colWidth,
				cols = col_Width.length,
				t = jQuery(this),
				classN = t.attr('class'),
				listsize = jQuery('> li', this).size(),
				percol = Math.ceil(listsize/cols),
				percol2 = percol,
				colnum = 0,
				wrap_id = 'column_list_container_';
			jQuery(this).wrap('<div id="' + wrap_id + (++y) + '" class="column_list_container row"></div>');
			for (var i = 0; i <= listsize; i++)
			{
				if (i >= percol2)
				{
					percol2 += percol;
					colnum++;
				}
				var eq = jQuery('> li:eq('+i+')',this);
				eq.addClass('li_col_'+ colnum);
				if (jQuery(this).is('ol'))
				{
					eq.attr('value', ''+(i+settings.startN))+'';
				}
			}
			jQuery(this).css({'float':'left', 'width':''+col_Width[0]+'px'});
			for (colnum = 1; colnum <= (cols -1); colnum++)
			{
				var list_tag = (jQuery(this).is('ol')) ? 'ol' : 'ul';
				jQuery('li.li_col_'+ colnum, this).appendTo('#' + wrap_id + y).wrapAll('<'+list_tag+' class="li_cont_'+colnum +' '+ classN+'" style="float:left; width:'+col_Width[colnum]+'px"></'+list_tag+'>');
			}
		});
	}
}


// extend jquery with teaxtarea maxlength function
jQuery.fn.limitMaxlength = function(options)
{
	var settings = jQuery.extend({
		attribute: 'maxlength',
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// event handler to limit the textarea
	var onEdit = function()
	{
		var textarea = jQuery(this);
		var maxlength = parseInt(textarea.attr(settings.attribute));
		if (textarea.val().length > maxlength)
		{
			textarea.val(textarea.val().substr(0, maxlength));
			// call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}
		// call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}
	this.each(onEdit);
	return this.keyup(onEdit).keydown(onEdit).focus(onEdit).live('input paste', onEdit);
}


// pre-popopulate forms function
function formPrePop(obj) {
	obj.find('input.pre_pop, textarea.pre_pop').each(function() {
		var label = $(this).prev('label').text();
		if ($(this).val() == '')
		{
			$(this).val(label);
			$(this).focus(function() {
				var tmp_val = $(this).val();
				if (tmp_val == label) {
					$(this).val("");
				}
			});
			$(this).blur(function() {
				var tmp_val = $(this).val();
				if (tmp_val == "" || tmp_val == null) {
					$(this).val(label);
				}
			});
		}
	});
}


// validate email
function checkEmail(val) {
	var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (regex.test(val)) { return true; }
	else { return false; }
}


// validate email
function checkPhone(val) {
	var cln_val = val.replace(/\D/g, '');
	if (cln_val.length >= 10) { return true; }
	else { return false; }
}

function countChecked() {
  var n = $("input:checked").length;
  //alert(n); 
  if (n>0) { return true;}
  else { return false; } 
}

// validate form
function validateForm(elem) {
	var submit = true;
	var this_form = $(elem).parents('form');
	// reset errors
	$(this_form).find('.error').hide();
	$(this_form).find('.errorchkbox').hide();

	var pageurll = window.location.href;
	if (pageurll.indexOf("/contact/") >= 0){
		var selIdx = document.forms[0].CurrentClient.selectedIndex;
    	var newSel = document.forms[0].CurrentClient.options[selIdx].value;
		var newSell = 'CC';
		if (newSel == 'Non-Client'){
			check_box = countChecked();
			if (!check_box) {
			submit = false;
			$(this_form).find('.errorchkbox').fadeIn(400);
			}
		} 
	}
	else {
		var newSel = 'Non-Client';
		var newSell = 'LM';		
	}
	var isDemo = '';
	// check for errors in input and textareas
	$(this_form).find('.required').each(function() {
		var input_val = $.trim($(this).val());
		if ($(this).attr('type') == 'text' && $(this).hasClass('name1')) {
			if (input_val == '') {
				submit = false;
				$(this).next('.error').fadeIn(400);
			}
		}
		if ($(this).attr('type') == 'text' && $(this).hasClass('name2')) {
			if (input_val == '') {
				submit = false;
				$(this).next('.error').fadeIn(400);
			}
		}
		if ($(this).attr('type') == 'text' && $(this).hasClass('company')) {
			if ((newSel == 'Non-Client') || (newSell == 'LM')){
				if (input_val == ''){ 
					submit = false;
					$(this).next('.error').fadeIn(400);
				}
			}
		}
		
		if ($(this).hasClass('bus_type')) {
			if ((newSel == 'Non-Client') || (newSell == 'LM')){
				if (input_val == ''){ 
					submit = false;
					$(this).next('.error').fadeIn(400);
				}
			}
		}
		
		if ($(this).hasClass('types')) {
			if (newSell == 'LM'){
				if (input_val == ''){ 
					submit = false;
					$(this).next('.error').fadeIn(400);
				}
			}
		}
		
		if ($(this).attr('type') == 'text' && $(this).hasClass('email_address')) {
			check_email = checkEmail(input_val);
			if (!check_email) {
				submit = false;
				$(this).next('.error').fadeIn(400);
			}
		}
		if ($(this).attr('type') == 'text' && $(this).hasClass('phone_number')) {
			check_phone = checkPhone(input_val);
			if (!check_phone) {
				submit = false;
				$(this).next('.error').fadeIn(400);
			}
		}
	});
	// check for errors with fields that must match
	$(this_form).find('.required_match').each(function() {
		var sibling = '#' + $(this).attr('rel');
		if ($(this).val() != $(sibling).val()) {
			submit = false;
			$(this).next('.error').fadeIn(400);
		}
	});
	return submit;
}


// obfuscate address
function obfsMail(s,e,h,c)
{
	var x = e + '&#x40;' + h;
	if (c == '') { c = x; }
	var y = 'href="ma' + 'ilto:' + x + '"';
	var z = (s == '') ? ('<a ' + y + '>' + c + '</a>') : ('<a class="' + s + '\' ' + y + '>' + c + '</a>');
	return z;
}


function formatTitle(title, currentArray, currentIndex, currentOpts)
{
	if (title) {
		var params = title.split('|');
		if ($.isArray(params))
		{
			var overlay_title = ((params[0] != '') && (params[0] != null) && (typeof params[0] != 'undefined')) ? '<strong>' + params[0] + ': </strong>' : '';
			var overlay_caption = ((params[1] != '') && (params[1] != null) && (typeof params[1] != 'undefined')) ? '<div class="overlay_caption">' + params[1] + '</div>' : '';
			return (overlay_title || overlay_caption) ? '<div class="overlay_title">' + overlay_title + 'Slide ' + (currentIndex + 1) + ' of ' + currentArray.length + overlay_caption + '</div>' : '';
		}
	}
}

// document onload routines
$(document).ready(function() {

	//init sub-nav centering
	if ($('#main_header').hasClass('tabbed_nav'))
	{
		if ($('#main_header .nav .current').length && $('#main_header .sub_nav ul').length)
		{
			var nav_p = $('#main_header .nav .current').position();
			var nav_w = $('#main_header .nav .current').width();
			var nav_c = Math.ceil(nav_p.left + (nav_w/2));
			var sub_w = $('#main_header .sub_nav ul').width();
			var em_h = $('#main_header .sub_nav ul li a').height();
			var margin = -(Math.ceil(sub_w/2) - nav_c + Math.ceil(em_h/4));
			$("#main_header .sub_nav ul").css( { "margin-left": margin+"px" } );
		}
	}

	if ($('#content_tabs').hasClass('tabbed_nav'))
	{
		if ($('#content_tabs .nav .current').length && $('#content_tabs .sub_nav ul').length)
		{
			var nav_p = $('#content_tabs .nav .current').position();
			var nav_w = $('#content_tabs .nav .current').width();
			var nav_c = Math.ceil(nav_p.left + (nav_w/2));
			var sub_w = $('#content_tabs .sub_nav ul').width();
			var em_h = $('#content_tabs .sub_nav ul li a').height();
			var margin = -(Math.ceil(sub_w/2) - nav_c + Math.ceil(em_h/4));
			$("#content_tabs .sub_nav ul").css( { "margin-left": margin+"px" } );
		}
	}
	
	// init slideshow
	var slide_fx = ($.browser.msie) ? 'none' : 'fade';
	$('#slideshow').cycle({
		cleartypeNoBg: true,
		fx: slide_fx,
		speed: 200,
		timeout: 8000,
		slideExpr: '.slide',
		pager: '.slideshow_nav',
		pauseOnPagerHover: 1
	});

	// init overlay triggers
	$('.overlay_trigger').fancybox({
		'padding'			: 0,
		'overlayOpacity'	: 0.8,
		'overlayColor'		: '#000',
		'titlePosition'		: 'inside',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titleFormat'		: formatTitle,
		'onStart'			: function() { $('#slideshow').cycle('pause'); },
		'onClosed'			: function() { $('#slideshow').cycle('resume'); }
	});
	
	// wrap buttons with extra markup
	$('a.button').wrapInner('<span class="button_inner"></span>');
	$('input.button').wrap('<div class="button"></div>');
	$('div.button').each(function(){
		$(this).click(function(e) {
			if ($(e.target).is('div')) { // prevent event bubbling
				$(this).children('input.button').click();
			}
		});
	});
	
	// init primary nav
	var active_menu_index = -1;
	$('#menu-primary-nav .menu-item').each(function(index) {
		if ($(this).hasClass('current-menu-item') || $(this).hasClass('current-menu-parent') || $(this).hasClass('current-page-ancestor'))
		{
			active_menu_index = parseInt(index);
			$(this).children('a').addClass('active');
		}
	});
	$('#menu-primary-nav .menu-item').each(function(index) {
		if (index == 0) {
			$(this).addClass('first-menu-item').append($('#needs_dropdown_menu')).wrapInner('<div class="dropdown-menu" />');
			//$(this).find('.nav_inner').wrapInner('<span class="has-children" />');
		}
		if (index == 1) {
			$(this).append($('#solutions_dropdown_menu')).wrapInner('<div class="dropdown-menu" />');
			$(this).find('.nav_inner').wrapInner('<span class="has-children" />');
		}
		if ((active_menu_index -1) == index) {
			$(this).addClass('active-sibling-right');
		}
		if ((active_menu_index +1) == index) {
			$(this).addClass('active-sibling-left');
		}
	});
	$('#menu-primary-nav .menu-item:last').addClass('last-menu-item');
	
	$('#menu-primary-nav .menu-item').hover(function() {
		$(this).addClass('menu-hover');
	}, function() {
		$(this).removeClass('menu-hover');
	});
	$('#menu-primary-nav .dropdown-menu').hover(function() {
		$(this).addClass('dropdown-hover');
	}, function() {
		$(this).removeClass('dropdown-hover');
	});
	
	// init column lists
	$('#needs_dropdown_menu .list_2_col').make_column_list({ colWidth: new Array(260,180) });
	$('#needs_dropdown_menu .list_3_col').make_column_list({ colWidth: new Array(250,220,200) });
	$('#needs_main_list ul').make_column_list({ colWidth: new Array(315,315) });
	
	// sync columns
	$('.dropdown_menu_box .col').syncHeight();
	$('#solutions_index .col').syncHeight();
	
	//add bkg color to every other tr of recent news table
	$('.striped_table tbody tr:odd').addClass('stripe_row');
	
	// init resource finder form
	$('#resource_finder select').change(function() {
		window.location = $(this).find('option:selected').val();
	});
	$('#resource_finder_search select').change(function() {
		document.resource_finder_search.submit();
	});
	// init form pre-populate
	$('form').each(function() {
		formPrePop($(this));
	});
	
	// form validation
	$('.validate_form input[type="submit"]').click(function() {
		return validateForm(this);
	});
	
	// clear error messages upon blur
	$('.validate_form .required').blur(function() {
		if ($(this).val() != '') {
			var next_error = $(this).next('.error');
			$(next_error).fadeOut(400, function() {
				$(next_error).removeClass('show_error');
			});
		}
	});
	
	// init toggling
	$('.toggle_details .trigger').click(function() {
		$(this).prev('.content').slideToggle();
		$(this).find('.open_label').toggle();
		$(this).find('.close_label').toggle();
		$(this).toggleClass('open');
		
		return false;
	});
	
	// init obfuscated addresses
	$('.obfm').each(function() {
		var $this = $(this);
		var params = $this.attr('rel').split(':');
		if (params[0] == 'obfm') {
			var addr = obfsMail('',params[1],params[2],'');
		}
		$this.html(addr);
	});

	// init textarea maxlengths
	var onEditCallback = function(remaining)
	{
		var char_cnt = $(this).siblings('.chars_remaining');
		char_cnt.text("Characters remaining: " + remaining);
		if (remaining > 0) {
			char_cnt.css('color', '#000000');
		} else {
			char_cnt.css('color', '#cc0000');
		}
	}
	var onLimitCallback = function()
	{
		$(this).siblings('.chars_remaining').css('color', '#cc0000');
	}
	$('textarea[maxlength]').limitMaxlength({
		onEdit: onEditCallback,
		onLimit: onLimitCallback
	});

	// init IE hacks
	if ($.browser.msie)
	{
		$('#main_infobar .module:last, #main_lower .module:last, #sidebar .module:last').addClass('last_module');
	}

	(function() {
/*		var elqCfg = document.createElement('script'); elqCfg.type = 'text/javascript'; elqCfg.async = true; elqCfg.src = '/elqNow/elqCfg.js';
		var elqCfg_s = document.getElementsByTagName('script')[0]; elqCfg_s.parentNode.insertBefore(elqCfg, elqCfg_s);
		var elqImg = document.createElement('script'); elqImg.type = 'text/javascript'; elqImg.async = true; elqImg.src = '/elqNow/elqImg.js';
		var elqImg_s = document.getElementsByTagName('script')[0]; elqImg_s.parentNode.insertBefore(elqImg, elqImg_s);*/
	})();

});

      $(document).ready(function() {
      $('div.demo-show:eq(0)> div').hide(); 
      $('div.demo-show:eq(0)> h5').click(function() {
      $(this).next().slideToggle('fast');
		 });
	 });

window.onload = function() {
    var links = document.getElementsByTagName('li');
    for (var i=0;i < links.length;i++) {
        if (links[i].className == 'new-window menu-item menu-item-type-custom menu-item-345') {
            links[i].onclick = function() {
				window.open("http://www.insperity.com/careers");
                return false;
            };
        }
    }
};
runOnLoad(function(){
  $("input#name1").focus();
});


