var timerid = false;
function hidesearch(){
	if(!$('#search_input input').is(':focus')){
		$('#search_input:visible').slideUp(200,function(){
			$('#search_input input').val('enter search term');
		});
	}
}
$(document).ready(function(){

	$('ul.tabs').each(function(){
		$(this).find('li').each(function(i){
			$(this).click(function(){
				$(this).parent().find('li').removeClass('active');
				$(this).addClass('active');
				$(this).parent().parent().find('.tabcontent .tab').removeClass('active');
				$(this).parent().parent().find('.tabcontent .tab').eq(i).addClass('active');
				return false;
			});
		});
	});
	$('#threats tr').bind('mouseenter',function(){
		var hidden = $(this).find('.hidden');
		hidden.slideDown(200);
		$('#threats tr .hidden').not(hidden).slideUp(200);
	});
	
	// window resize
	resizehandler();
	$(window).resize(resizehandler);
	
	// nav bar
	$('#nav_library, #nav_tools').mouseover(function(){
		$('#nav ul.dropdown:visible').not($(this).find('ul.dropdown')).hide();
		if(!$(this).find('ul.dropdown').is(':visible')){
			var drop = $(this).find('ul.dropdown');
			if(drop.width() < 170){
				drop.width(170);
			}
			drop.css('opacity',0.9).slideDown(200);
		}
	});
	
	$('#nav_tools > a').click(function(){
		return false;
	});
	
	// no glow for ie6
	if($.browser.msie && $.browser.version.substr(0,1)<7) {
		$('.glow').remove();
	}
	
	// search
	$('#nav_search').mouseover(function(){
		$('#nav ul.dropdown').hide();
		$('#search_input').slideDown(200).focus();
	});
	
	$('#search_input input').val('enter search term').focus(function(){
		if($(this).val() == 'enter search term'){
			$(this).val('');
		}
	});
	
	$('#nav').mouseover(function(){
		if(timerid){
			clearTimeout(timerid);
			timerid = false;
		}
	});
	
	$('#nav').bind('mouseleave',function(e){
		$('#nav ul.dropdown:visible').slideUp(300);
		// add short delay to search hide to improve usability
		timerid = setTimeout('hidesearch()',500);
	});
	
	$('#search_input input').blur(function(){
		hidesearch();
	}).keydown(function(e){
		if(e.keyCode == 13){ // enter key
			startsearch();
		}
	});
	
	$('#nav_search').click(function(){
		startsearch();
		return false;
	});
	
	// callouts
	resizecallouts();
	
	// columns fix for explorer
	if($.browser.msie){
		$('.columns').removeClass('columns').each(function(){
			var narrow = $(this).hasClass('narrow');
			
			if(narrow){
				var split1 = parseInt($(this).height()/2);
			}
			else{
				var split1 = parseInt($(this).height()/3);
				var split2 = 2*split1;
			}
			
			//alert(split1+' : '+split2+' : '+$(this).height());
			
			var column1 = '';
			var column2 = '';
			var column3 = '';
			
			var column = 1;
			
			$(this).contents().each(function(){
				var html;
				
				if(this.nodeType == 3){
					html = this.nodeValue;
				}
				else{
					html = $(this).html();
					
					if(narrow){
						if($(this).position().top < split1){
							column = 1;
						}
						else{
							column = 2;
						}
					}
					else{
						if($(this).position().top < split1){
							column = 1;
						}
						else if($(this).position().top > split1 && $(this).position().top < split2){
							column = 2;
						}
						else{
							column = 3;
						}
					}
				}
				
				if(column==1){
					column1 += html;
				}
				else if(column == 2){
					column2 += html;
				}
				else{
					column3 += html;
				}
			});
			
			if(narrow){
				$(this).html('<div class="column first">'+column1+'</div>'+'<div class="column last">'+column2+'</div>');
			}
			else{
				$(this).html('<div class="column first">'+column1+'</div>'+'<div class="column">'+column2+'</div>'+'<div class="column last">'+column3+'</div>');
			}
		});
		
	}
	
	// inline popup for filtering page
	$("#ctable table").hide();
	$("#ctable a.button").click(function(){
		inlinedisplay('<table>'+$(this).parent().parent().find('table').html()+'</table>');
		return false;
	});
	
	// truncate updates
	$('.updates').not('.updatepage').each(function(){
		var maxheight = 0;
		$(this).parent().children().not(this).each(function(){
			if(maxheight < $(this).height()){
				maxheight = $(this).height();
			}
		});
		if(maxheight + 500 < $('.updates').height()){
			$('.updates').data('maxheight',$('.updates').height()).data('minheight',maxheight).height(maxheight).append('<a href="#" class="expander">More</a>');
		}
	});
	
	$('.updates .expander').toggle(function(){
		$(this).text('Less').parent().animate({height: $(this).parent().data('maxheight')+25},1000);
	},function(){
		$(this).text('More').parent().animate({height: $(this).parent().data('minheight')},1000);
	});
	
	$('.expander').not('.updates .expander').click(function(){
		if(!$(this).hasClass('expanded')){
			$(this).parent().find('.hidden').slideDown(300);
			$(this).addClass('expanded');
		}
		else{
			$(this).parent().find('.hidden').slideUp(300);
			$(this).removeClass('expanded');
		}
	});
	
	// table expander
	
	$('table.data.expand').each(function(){
		if($(this).find('tr').length > 5){
			$(this).wrap('<div class="tableexpand">').after('<a href="#" class="expander">More</a>').wrap('<div class="tableclip">');
		}
	});
	
	// set tableexpand to 5 tr heights initially
	$('.tableclip').each(function(){
		var height = 0;
		$(this).find('table tr').slice(0,5).each(function(){
			height += $(this).height();
		});
		$(this).height(height);
		
		$(this).parent().data('num',5);
	});
	
	$('.tableexpand .expander').click(function(){
		var num = $(this).parent().data('num') + 10;
		$(this).parent().data('num',num);
		
		var height = 0;
		$(this).parent().find('table tr').slice(0,num).each(function(){
			height += $(this).height();
		});

		$(this).parent().find('.tableclip').animate({height: height},400);
		
		if(num >= $(this).parent().find('table tr').length){
			$(this).remove();
		}
		
		return false;
	});
	
	// papers expand
	$('.papers a.bubble').each(function(){
		if($(this).parent().find('.expand').length > 0){
			$(this).toggle(function(){
				$(this).parent().find('.expand').slideDown(200);
			},function(){
				$(this).parent().find('.expand').slideUp(200);
			});
		}
	});
	
	// add fixed width to data tables to force word-break
	$('table.data').each(function(){
		if($(this).width() > $(this).parent().width()){
			var cellwidth = $(this).parent().width()/$(this).find('tr').eq(0).find('td').length; // divide widths evenly amongst cells
			cellwidth = Math.floor(cellwidth) - 40; // 40px padding on cells
			$(this).find('td').width(cellwidth);
		}
	});
	
	// style all checkboxes
	$('input:checkbox, #pagefooter select').uniform();
	
	// show hidden tab if internal link is hidden
	var href = window.location.href;
	var hash = href.split('#');
	if(hash.length > 1){
		showInternal(hash[1]);
	}
	
	// scroll to link
	$('a[href*=#]').click(function(){
		var href = $(this).attr('href');
		if(href[0] == '#'){ // highlight for internal links only
			showInternal(href.substring(1));
			return false;
		}
	});
	
	// contact form
	$('#contactselect').change(function(){
		var option = $(this).find('option:selected');
		if(option.hasClass('link')){
			showInternal(option.attr('value').split('#')[1]);
			window.location.href = option.attr('value');
		}
		else if(option.hasClass('form')){
			// add captcha if none exist (generate captcha only as needed)
			if($('#contactcaptcha').html() == ''){
				$('#contactcaptcha').html('<img width="180" height="30" alt="captcha" src="/forms/captcha/use-captcha.php" id="contactcaptchaimage" />');
			}
			$('#contactmailto').attr('value',option.attr('title')); // set flag for recipient email
			
			$('#footerlinks, #vulnerabilityform').hide();
			$('#contactmessage').show().html(option.attr('value'));
			$('#contactform').show().css('background-color','#515f6a').animate({backgroundColor: "#141e26"},500);
		}
		else if(option.hasClass('vulnerabilityform')){
			// add captcha if none exist (generate captcha only as needed)
			if($('#vulnerabilitycaptcha').html() == ''){
				$('#vulnerabilitycaptcha').html('<img width="180" height="30" alt="captcha" src="/forms/captcha/use-captcha.php" id="vulnerabilitycaptchaimage" />');
			}
			$('#vulnerabilitymailto').attr('value','VUL'); // set flag for recipient email
			
			$('#footerlinks, #contactform').hide();
			$('#contactmessage').show().html(option.attr('value'));
			$('#vulnerabilityform').show().css('background-color','#515f6a').animate({backgroundColor: "#141e26"},500);
		}
		else if(option.hasClass('text')){
			$('#footerlinks').hide();
			$('#contactform').hide();
			$('#contactmessage').show().html(option.attr('value')).css('background-color','#515f6a').animate({backgroundColor: "#0a0f13"},500);
		}
		
		$(this).find('option').eq(0).attr('selected','selected');
		$.uniform.update($(this));
	});
	
	$('#submitcontactform').click(function(){
		$.ajax({
			type: 'POST',
			url: '/forms/contactus.php',
			data: $('#contactform').serialize(),
			success: function(msg){
				$('#contactmessage').text(msg).css('background-color','#515f6a').animate({backgroundColor: "#0a0f13"},500);
				refreshcontactcaptcha();
			},
			error: function(){
				$('#contactmessage').text('Connection error, please check your internet connection').css('background-color','#515f6a').animate({backgroundColor: "#0a0f13"},500);
				refreshcontactcaptcha();
			}
		});

		return false;
	});
	
	$('#submitvulnerabilityform').click(function(){
		$.ajax({
			type: 'POST',
			url: '/forms/contactus.php',
			data: $('#vulnerabilityform').serialize(),
			success: function(msg){
				$('#contactmessage').text(msg).css('background-color','#515f6a').animate({backgroundColor: "#0a0f13"},500);
				refreshcontactcaptcha();
			},
			error: function(){
				$('#contactmessage').text('Connection error, please check your internet connection').css('background-color','#515f6a').animate({backgroundColor: "#0a0f13"},500);
				refreshcontactcaptcha();
			}
		});

		return false;
	});
});

function refreshcontactcaptcha(){
	d = new Date();
	$("#contactcaptchaimage:visible").attr("src", $("#contactcaptchaimage").attr("src")+"?"+d.getTime());
	$("#vulnerabilitycaptchaimage:visible").attr("src", $("#vulnerabilitycaptchaimage").attr("src")+"?"+d.getTime());
	$("#contactcaptchacode, #vulnerabilitycaptchacode").attr("value","");
}

// navigate to internal link
function showInternal(hash){
	$('#main a').each(function(){
		if($(this).attr('name') == hash){
			// switch tab if anchor is in a hidden tab
			var mytab = $(this).parents('.tab').eq(0);
			if(!mytab.hasClass('.active') && $(this).parents('.tabcontent').length > 0){
				var tabs = $(this).parents('.tabcontent').find('.tab');
				
				tabs.removeClass('active');
				mytab.addClass('active');
				var index = tabs.index(mytab);
				
				$(this).parents('.tabcontent').parent().find('ul.tabs li').removeClass('active').eq(index).addClass('active');
			}
			
			var highlight; // flash a brief highlight to show where link is
			if(mytab.length > 0){
				highlight = mytab;
			}
			else{
				highlight = $(this).parent();
			}
			
			// scroll to anchor
			var top = $(this).offset().top;
			$('html, body').animate({scrollTop: top}, 300,function(){
				// flash anchor parent				
				highlight.css('background-color','#fda').animate({backgroundColor: "#eee"},500,function(){
					$(this).css('background-color','transparent');
				});
				
			});
			
			return false;
		}
	});
}

function startsearch(){
	if($('#search_input input').val() != 'enter search term'){
		window.location = '/search.php?action=search_all&data='+$('#search_input input').val();
	}
}

function resizehandler(){
	if($(window).width() > 1260){
		$('.wrapper').addClass('wide');
	}
	else{
		$('.wrapper').removeClass('wide');
	}
	resizecallouts();
}

function resizecallouts(){
	$('img.callout').each(function(){
		if($(this).width() > $(this).parent().width()){
			$(this).data('width',$(this).width());
			$(this).width($(this).parent().width());
		}
		else{
			if($(this).data('width') && $(this).data('width') < $(this).parent().width()){
				$(this).width($(this).data('width'));
			}
		}
	});
}

// inline popup
function inlinedisplay(html){
	$('body').append('<div id="fullscreen"><div id="fillbackground"></div><div id="pop"><a href="#" id="fullclose"></a>'+html+'</div></div>');
	$('#pop').css('top',($(window).scrollTop() + 100) + 'px');
	
	$('#fullclose').click(function(){
		$('#fullscreen').fadeOut(400,function(){
			$(this).remove();
		});
		return false;
	});
}

/* nvc toggle - legacy */
function toggle(str){
	if($('#div'+str).is(':visible')){
		$('#div'+str).removeAttr('style').slideUp(200);
	}
	else{
		$('#div'+str).removeAttr('style').slideDown(200);
	}
	
	var img = $('#img'+str);
	
	if(img.hasClass('active')){
		img.removeClass('active').attr('src','/images/red_plus.gif');
	}
	else{
		img.addClass('active').attr('src','/images/red_minus.gif');
	}
}

function addmessage(data){
	if($('.messages').length == 0){
		$('#main').prepend('<ul class="messages"></ul>');
	}
	$('.messages').append('<li style="display: none">'+data+'</li>');
	$('.messages li:last').slideDown('quick');
}

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-24513516-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; 
ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 
'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(ga, s);
  })();

