/*
	functions.dom.js
	DOM Interactivity Functions
	Created: 1.14.08
	Creator: Matt Kircher, Mainline Media LLC
*/

function translateEmails(){
	$('span.liame').each(function(){
		var spt = $(this);
		var at = / at /;
		var dot = / dot /g;
		var addr = $(spt).text().replace(at,"@").replace(dot,".");
		
		var t = $(spt).attr('title');
		
		var subject = t.substring(t.indexOf('|')+1);
		fulladdr = ($.trim(subject) != "")?addr+'?subject='+subject:addr;
		
		var title = "Send an email";
		var altContent = t.substring(0, t.indexOf('|'));
		var content = ($.trim(altContent) != "")?altContent:addr
		
		$(spt).after('<a href="mailto:'+fulladdr+'" title="'+title+'">'+ content +'</a>')
		.hover(function(){window.status="Send a letter!";}, function(){window.status="";});
		$(spt).remove();
	});
}

function setFontSize(value, expires, path, domain, secure){
	var today = new Date(); today.setTime( today.getTime() );
	expires = 1 * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (expires) );	
	document.cookie = "fontSize=" +escape( Number(value) ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
function getFontSize(){
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ ){
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if(cookie_name == 'fontSize' ){
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 ){ cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') ); }
			return String(Number(cookie_value)+"px");
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ){ return "11px"; }
}

function setupPage(){
		
	//IE6 Flickering fix
	try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}
	
	//rounded_buttons
	/*if((BrowserDetect.browser != "Explorer") || 
	   (BrowserDetect.browser == "Explorer" && 
	    BrowserDetect.version > 6)){ roundButtons(); }*/
	
	//navigation
	$('#main-nav li:last, #sub-nav li:last, #functional-nav li:last, #footer-main-nav li:last, #footer-functional-nav li:last').addClass('end_nav');
	
	if(BrowserDetect.browser == "Opera"){
		//fix functional nav position...
		$('#functional-nav').css({ backgroundPosition:'top right', marginLeft:'200px', width:'475px', top:'0px' });
		$('#functional-nav ul li').css({ position:'relative', top:'-15px !important'});
	}
	
	if($('#sub-nav').length){
		$('#sub-nav a').not(':first').hover(
			function(){ $(this).parent().addClass('gradient_down'); },
			function(){ $(this).parent().removeClass('gradient_down'); }
		);
		$('#sub-nav a:first').hover(
			function(){ $(this).parent().addClass('gradient_up'); },
			function(){ $(this).parent().removeClass('gradient_up'); }
		);
	}
	
	//add side pieces to page
	$('#masthead').prepend('<div id="masthead_left_piece"></div>');
	$('#masthead').prepend('<div id="masthead_right_piece"></div>');
	$('#footer').prepend('<div id="footer_right_piece"></div>');
	
	$('.module:first').filter('.scape1, .clipboard, .survey, .doctor').addClass('notop_module');
	$('.module:first').css('padding-top','25px');
	
	//misc. other stuff
	
	/*font-sizer*/
	var sizer = $('<div id="font-sizer"><div>');
	$(sizer)
	.append('<b>Font Size:</b>&nbsp;&nbsp;')
	.append('<a href="#" title="Normal font size">T</a>')
	.append('<a href="#" title="Larger font size">T</a>')
	.append('<a href="#" title="Largest font size">T</a>')
	.find('a:eq(0)').css({fontSize:'10px'}).click(function(){ $('body').css({ fontSize:'11px' }); setFontSize(11, 30, '/', '', ''); setupHeights(); return false; }).end()
	.find('a:eq(1)').css({fontSize:'11px'}).click(function(){ $('body').css({ fontSize:'12px' }); setFontSize(12, 30, '/', '', ''); setupHeights(); return false; }).end()
	.find('a:eq(2)').css({fontSize:'12px'}).click(function(){ $('body').css({ fontSize:'13px' }); setFontSize(13, 30, '/', '', ''); setupHeights(); return false; }).end()
	.find('a').css({ color:'#999', fontFamily:'Georgia, Times, "Times New Roman", serif' }).after('&nbsp;&nbsp;').end()
	.css({ color:'#CCC', font:'10px Verdana, Arial, sans-serif', position:'relative', top:'-30px', marginBottom:'-30px', float:'right' });
	
	$('body').css({ fontSize:getFontSize() });	//update body font size
	
	$('#main-content').prepend($(sizer)); //append sizer
	/*----*/
	
	$('.tricolumn div:first').addClass('start_column');
	$('.tricolumn div:last').addClass('end_column');
	$('.bicolumn').find('div:last').addClass('end_column');	
	$('.bicolumn').each(function(){
		if($(this).parent().attr('id') == "preamble" || 
		   $(this).parent().attr('id') == "amble"){ $(this).after('<div class="clear_block"></div>')}
	 });
	
	$('.home #masthead-content h3').addClass('highlight_drkblue');
	if(BrowserDetect.OS == "Mac" && (BrowserDetect.browser == "Safari" || BrowserDetect.browser == "Firefox")){ 
	   	$('#main-nav').css('top', '58px');
	}
	$('a').bind('click', function(){ $(this).blur(); });
	$('#home_jump_area').append('<div class="clear_block"></div>');
	
	//double inline column
	if(BrowserDetect.browser == "Explorer"){
		$('.double_column_list').each(function(){
			var s = eval($(this).find('li').length / 2) - 1;
			var l = $(this).find('li:gt('+s+')');
			$('<ul></ul>').insertAfter($(this));
			$(this)
			.css({float:'left', width:'45%'}).next()
			.css({float:'right', width:'45%'}).html(l)
			.after('<div class="clear_block"></div>');
		});
	} else {
		$('.double_column_list').after('<div class="clear_block"></div>');
	}
		
	//FAQ
	if($('#faq').length){
		
		$('#sub-content').prepend('<div id="faq-jump" class="module bright"><h4>FAQ Quick Jump</h4></div>');
		var count = 1;
		$('#faq h3').each(function(){
			$(this).attr('id','faq'+count).addClass('subhead');
			$('#faq-jump').append('<p><a href="#faq'+count+'">'+$(this).text()+'</a></p>');
			count++;
		});
		$('#faq h3:gt(1)').before('<p><a href="#faq-jump" title="Go to the top of the page...">Back to the Top</a></p>');
		$('a[@href="#faq-jump"]').bind('click', function(){
			$('html, body').animate({scrollTop:0}, 'slow');
		});
	}
	
	//testimonials
	if($('#testimonials').length){
		$('#testimonials blockquote:first-line').wrap('<b></b>');
		$('#testimonials cite:gt(0)').append('<br /><br /><b><a href="#header" title="Go to the top of the page...">Back to the Top</a></b>');
		$('a[@href="#header"]').bind('click', function(){
			$('html, body').animate({scrollTop:0}, 'slow');
		});
	}
	
	//news
	if($('#news-listings').length){
		
		var entry_chunk_size = 5;
		
		$('#sub-content').prepend('<div id="news-jump" class="module bright"><h4>Recent News</h4></div>');
		var count = 1;
		$('.news_entry:lt('+entry_chunk_size+')').each(function(){
			$(this).attr('id','news'+count);
			var title = $(this).find('h4').text();
			var date = $(this).find('h3').text();
			$('#news-jump')
			.append('<p><a href="#news'+count+'">'+title+'</a> <br /><sup>('+date+')</sup></p>')
			.bind('click', {'newPage':0}, function(event){
				currentPage = event.data['newPage'];
				paginate();
				setupHeights();
				$('#pager').filter('a:eq('+currentPage+')').addClass('active').siblings().removeClass('active');
			});
			count++;
		});		
		$('a[@href="#news-jump"]').bind('click', function(){
			$('html, body').animate({scrollTop:0}, 'slow');
		});
		
		
		//PAGINATION CODE
		//-----------------------------
		var currentPage = 0;
		var numPer = entry_chunk_size;			
		var paginate = function(){
			$('#news-listings').find('.news_entry').show();
			$('.news_entry:lt('+eval(currentPage*numPer)+')').hide();
			$('.news_entry:gt('+eval((currentPage + 1) * numPer-1)+')').hide();
		};
		
		var numEntries = $('#news-listings').find('.news_entry').length;
		var numPages = Math.ceil(numEntries / numPer);
		var pager = $('<div id="news-pager"><b>Page:</b> </div>');
		
		//setup page buttons
		for(p=0; p<numPages; p++){
			$('<a class="page_number">'+(p+1)+'</a>')
			.bind('click', {'newPage':p}, function(event){
				currentPage = event.data['newPage'];
				paginate();
				setupHeights();
				$('#news-pager a:eq('+currentPage+')').addClass('active').siblings().removeClass('active');
			})
			.appendTo(pager).addClass('clickable');
		}
		
		pager.insertBefore($('#news-listings'));
		$('#news-pager a:eq('+currentPage+')').addClass('active');
		paginate();
		//-----------------------------
		
		$('#news-listings').after('<p><a href="#news-jump" title="Go to the top of the page...">Back to the Top</a></p>');
	}
}
function setupHeights(){
	
	if($('#content').height() < $('#main-content').outerHeight() ||
	   $('#content').height() < $('#sub-content').outerHeight()){		
		$('#content')[0].style.height = eval($('#main-content').outerHeight())+"px";
		if($('#sub-content').length > 0){
			if(BrowserDetect.browser == "Explorer"){
				$('#sub-content')[0].style.height = '1px';
			}
			$('#sub-content')[0].style.height = eval($('#main-content').outerHeight())+"px";
		}
	} else {		
		if($('#sub-content').length > 0){
			if(BrowserDetect.browser == "Explorer"){
				$('#sub-content')[0].style.height = '1px';
			}
			$('#sub-content')[0].style.height = eval($('#content').height())+"px";
		}
	}
	$(document).bind('resize', setupHeights);
}

function setupProcessDiagram(){
	if($('#process_diagram').length){
		
		$('#process_diagram ol li:eq(0)')
			.wrapInner('<span></span>').find('a').prependTo('.p1').end()
		.next().wrapInner('<span></span>').find('a').prependTo('.p2').end()
		.next().wrapInner('<span></span>').find('a').prependTo('.p3').end()
		.next().wrapInner('<span></span>').find('a').prependTo('.p4').end()
		.next().wrapInner('<span></span>').find('a').prependTo('.p5').end()
		.next().wrapInner('<span></span>').find('a').prependTo('.p6').end()
		.next().wrapInner('<span></span>').find('a').prependTo('.p7');
		
		for(x=1; x<8; x++){
			$('<img src="images/process_diagram_step'+x+'_bg.jpg" />').css({display:'none'}).appendTo('body');
			$('<img src="images/process_diagram_step'+x+'_bg_over.jpg" />').css({display:'none'}).appendTo('body');
		}
		
		$('#process_diagram').append('<div id="process_diagram_info"><h4>Survey Process Lifecycle</h4><p>With your mouse, rollover each step to the left to learn more about it.</p></div>');		
		$('#process_diagram a').each(function(){
			
			var content = $(this).parent().find('span').text();
			content = String(content.substring(content.indexOf(" - ")+3));
							   
			$(this)
			.bind('mouseover', function(){			
				
				$('#process_diagram ol a').removeClass('selected');
				$(this).addClass('selected');
				
				$('#process_diagram_info')
				.empty()
				.append('<h4>'+$(this).text()+'</h4>')
				.append('<p>'+content+'</p>')
				.append('<p><a href="'+$(this).attr('href')+'" title="Jump to this step for more information">View this step</a></p>')
			});
		});
	}
}

/* CONTACT FORM */

function setupContactForm(){
	if($('#contactForm').length){
				
		//remove required attention classes from required fields
		$('#contactForm .required').bind('change', function(){
			if($.trim($(this).val()) != ""){
				$(this).removeClass('required_attention');
				if($(this).get(0).nodeName == "SELECT"){
					if($(this).next().attr('class') == "select_required_attention"){
						$(this).next().remove();
					}
				}
			}
		});
		
		//bind blur / focus actions
		if(!$.browser.msie){
			$('#contactForm input[@type="text"]')
			.bind('focus', function(){ $(this).addClass('highlighted_form_field'); })
			.bind('blur', function(){  $(this).removeClass('highlighted_form_field'); });
		}
		
		//set focus to first form field
		$('#contactForm input[@tabindex="1"]').focus();
	}
}
function validateContactForm(){
	
	//setup valid object
	var valid = { status:true, response:'', element:null };
	
	//remove classes, go through and check for non-values
	$('#contactForm .required').removeClass('required_attention');
	$('#contactForm .select_required_attention').remove();
	$('#contactForm .required').each(function(){
		if(($(this).val() == "" || $(this).val() == null)){
			$(this).addClass('required_attention');
			valid.status = false;
			valid.response = 'One or more required fields has not been completed. Please complete them and resubmit the form.';
			if(valid.element == null){ valid.element = $(this); }
			
			if($(this).get(0).nodeName == "SELECT"){
				$(this).after('<span class="select_required_attention">&lsaquo;&mdash;</span>');
			}
		}
	});
	
	//if email is not of the form 'name@email.com', don't validate
	if(valid.status){
		$('#contactForm .required').each(function(){
			if($(this).attr('name') == "email"){
				
				if(!validateEmail($(this).val())){
					$(this).addClass('required_attention');
					valid.status = false;
					valid.response = 'Please supply a valid email address.';	
					valid.element = $(this);
				}
			}
		});
	}
	
	//display alert, focus on first non-valued field
	if(!valid.status){ alert(valid.response); $(valid.element).focus(); }
	return valid.status;
}

/* OTHER FORMS */

function validateEmail(e){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test($.trim(e));
}

function validateNewsletterSignup(){
	var email_field = $('#newsletterSignup input[@name="email"]');
	if(!validateEmail(email_field.val())){
		email_field.focus();
		alert('Please supply a valid email address.');
		return false;
	} else { 
		return true;
	}
}

/* IE RELATED */

function applyIE6FlickerFix(){
	try {
	  document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {}
}

//DOM loaded
$(document).ready(function(){
	BrowserDetect.init();
	translateEmails();
	setupPage();
	setupProcessDiagram();
	setupContactForm();
	applyIE6FlickerFix();//IE BG-image flicker fix	
});
window.onload = function(){
	setupHeights();
}