//var bgImageLoaded = false;
$(function(){
	initTabs();
	textChanger.init();
  $('.gallery .holder ul').cycle({
    timeout:6000,
    pager:'.gallery .switcher',
    pagerAnchorBuilder: AnchorBuilder,
    cleartypeNoBg:true
  });
  $('.connect-box .socials').css('margin-left','-'+$('.connect-box .socials').width()+'px').show();
  $('.open-close').click(function(e){
    e.preventDefault();
    var currentlyClosed = ($('.connect-box .socials').css('margin-left') == '-'+$('.connect-box .socials').width()+'px');
    $('.connect-box .socials').animate({marginLeft:(currentlyClosed?0:-1*$('.connect-box .socials').width())},350);
  });
  //$('#bg').ready(function(){ bgImageLoaded = true;});
  initResize();
  WirePlaceholders();
  /*$('a:external').click(function(){
    return(exitMsg());
  });*/
  $('.int-nav li:first').addClass('first');
  $('.int-nav li:last').addClass('last');
  HackIssues();
  HackNewsPage();
  $('.sharea .print').corner('2px');
  $('a:not([href])').css('color','#000');
  $('a.lightbox > img').parent().lightBox();
  $('.gallery a[href^=v://]').lightBox({video: true});
  $('.main-scroller a[href^=file://]').each(function(){
    var link = $(this).attr('href');
    $(this).attr('href', link.replace('file://',''));
  });
  $('input[name=EventTypeID]').val($('input[id$=EventTypeIDs]').val());          $('input[name=DocumentTypeID]').val($('input[id$=DocumentTypeIDs]').val());      if($.url.param('EventTypeID') != null)  {    $('select#ArchiveEvType').val(decodeURIComponent($.url.param('EventTypeID')));  }  if($.url.param('Subcommittee') != null)  {    $('select#SubSelect').val(decodeURIComponent($.url.param('Subcommittee')));  }  if($.url.param('q') != null)  {    $('input#resbox').val(decodeURIComponent($.url.param('q').replace(/[+]/g," ")));  }  if($.url.param('SearchPhrase') != null)  {    $('input#SearchPhrase').val(decodeURIComponent($.url.param('SearchPhrase').replace(/[+]/g," ")));    //$(this).html($(this).html().replace(/[+]/g," "));  }  $('select[name=Congress]').val($.url.param('Congress'));  iCalFlyout();});
function AnchorBuilder(index, slideElement)
{ return '<li><a href="#">' + (index+1) + '</a></li>'; }

$(window).resize(function(){
	initResize();
});

function iCalFlyout()
{
  $('.ical').each(function(){
    var icalMenu = $(this);
    icalMenu.find('.cal-btn').click(function(e){
      e.preventDefault();
      icalMenu.find('.cal-drop').fadeIn();
    });
    icalMenu.find('.close, .cal-drop a').click(function(){
      icalMenu.find('.cal-drop').fadeOut();
    });
  });
}

/* IE Hover */ 

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 u=k(){9 g=/^([^#.>`]*)(#|\\.|\\>|\\`)(.+)$/;k u(a,b){9 c=a.J(/\\s*\\,\\s*/);9 d=[];n(9 i=0;i<c.l;i++){d=d.v(o(c[i],b))};6 d};k o(a,b,c){a=a.z(" ","`");9 d=a.r(g);9 e,5,m,7,i,h;9 f=[];4(d==8){d=[a,a]};4(d[1]==""){d[1]="*"};4(c==8){c="`"};4(b==8){b=E};K(d[2]){w"#":7=d[3].r(g);4(7==8){7=[8,d[3]]};e=E.L(7[1]);4(e==8||(d[1]!="*"&&!x(e,d[1]))){6 f};4(7.l==2){f.A(e);6 f};6 o(7[3],e,7[2]);w".":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};7=d[3].r(g);4(7!=8){4(e.j==8||e.j.r("(\\\\s|^)"+7[1]+"(\\\\s|$)")==8){q};m=o(7[3],e,7[2]);f=f.v(m)}y 4(e.j!=8&&e.j.r("(\\\\s|^)"+d[3]+"(\\\\s|$)")!=8){f.A(e)}};6 f;w">":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};m=o(d[3],e,">");f=f.v(m)};6 f;w"`":5=p(b,d[1]);n(i=0,h=5.l;i<h;i++){e=5[i];m=o(d[3],e,"`");f=f.v(m)};6 f;M:4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};f.A(e)};6 f}};k p(a,b){4(b=="*"&&a.F!=8){6 a.F};6 a.p(b)};k x(a,b){4(b=="*"){6 N};6 a.O.G().z("P:","")==b.G()};6 u}();k Q(a,b){9 c=u(a);n(9 i=0;i<c.l;i++){c[i].R=k(){4(t.j.H(b)==-1){t.j+=" "+b}};c[i].S=k(){4(t.j.H(b)!=-1){t.j=t.j.z(b,"")}}}}4(D.I&&!D.T){D.I("U",V)}',58,58,'||||if|listNodes|return|subselector|null|var||||||||limit||className|function|length|listSubNodes|for|doParse|getElementsByTagName|continue|match||this|parseSelector|concat|case|matchNodeNames|else|replace|push|childNodes|nodeType|window|document|all|toLowerCase|indexOf|attachEvent|split|switch|getElementById|default|true|nodeName|html|hoverForIE6|onmouseover|onmouseout|opera|onload|ieHover'.split('|'),0,{}))
/*parametrs [selector, hover_class]*/
function ieHover() {
	hoverForIE6("ul#nav li, .switcher li", "hover");
}

/* PNG Fix */
var transparentImage = "images/none.gif";
function fixTrans()
{
	if (typeof document.body.style.maxHeight == 'undefined') 
	{
		var imgs = document.getElementsByTagName("img");
		for (i = 0; i < imgs.length; i++)
		{	
			if (imgs[i].src.indexOf(transparentImage) != -1)
			{
				return;
			}
			if (imgs[i].src.indexOf(".png") != -1)
			{
				var src = imgs[i].src;
				imgs[i].src = transparentImage;
				imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
				imgs[i].style.display = "inline-block";
			}
		}	
	}
}

if (document.all && !window.opera)
	attachEvent("onload", fixTrans);

/* Tabs */
function initTabs()
{
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							for (var i = 0; i < this.tabs.length; i++)
							{
								var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
								if (tab)
								{
									tab.style.display = "none";
								}
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}

/* Font Resize */
var textChanger = {
	defaultFS : 1.2,
	init: function() {
		var el = document.getElementsByTagName("body")[0];
		var sz = textChanger.getCookie();
		el.style.fontSize = sz ? sz + 'em' : textChanger.defaultFS + 'em';
		var incr = document.getElementById('increase');
		if(incr)
			incr.onclick = function(){textChanger.changeSize(1); return false;};
		var decr = document.getElementById('decrease');
		if(decr)
			decr.onclick = function(){textChanger.changeSize(-1); return false;};
		var reset = document.getElementById('reset');
		if(reset)
			reset.onclick = function(){textChanger.changeSize(0); return false;};
	},
	changeSize: function(val) {
		var el = document.getElementsByTagName("body")[0];
		var size = el.style.fontSize.substring(0, 4);
		var fSize = parseFloat(size, 10);
		if (val == 1)	{
			fSize += 0.1;
			if (fSize > textChanger.defaultFS*1.5) fSize = textChanger.defaultFS*1.5;
		} 
		if (val == -1) {
			fSize -= 0.1;
			if (fSize < textChanger.defaultFS/1.5) fSize = textChanger.defaultFS/1.5;
		}       
		if (val == 0) fSize = textChanger.defaultFS;
		el.style.fontSize = fSize.toFixed(2) + 'em';
		textChanger.updateCookie(fSize);
	},
	updateCookie: function(vl)	{
		var today = new Date();
		var exp = new Date(today.getTime() + (365*24*60*60*1000));
		document.cookie = 'textChangerL=size=' + vl + ';' +'expires=' + exp.toGMTString() + ';' +'path=/';
	},
	getCookie: function()	{ 
		var cname = 'textChangerL=size=';   
		var start = document.cookie.indexOf(cname);
		var len = start + cname.length;
		if ((!start) && (cname != document.cookie.substring(0,cname.length))) {return null;}
		if (start == -1) return null;
		var end = document.cookie.indexOf(";",len);
		if (end == -1) end = document.cookie.length;
		return unescape(document.cookie.substring(len, end));
	}
}
	
/* Main Background */
/*var view;
function initResize() {
	view = document.getElementById("bg");
	if(view) {
		view.width = view.clientWidth;
		view.height = view.clientHeight;
		initBg();
		setTimeout("initBg()", 10);
	}
}
function initBg() {
	var w = document.documentElement.offsetWidth;
	var h = document.documentElement.offsetHeight;
	var pictureRatio = view.width/view.height;
	var screenRatio = w/h;
	
	if(screenRatio > pictureRatio) {
		view.style.width = w + "px";
		view.style.height = w/pictureRatio + "px";
		view.style.left = 0 + "px";
		view.style.top = h/2-view.height/2 + "px";
		view.width = w;
		view.height = w/pictureRatio;
	}
	else {
		view.style.height = h + "px";
		view.style.width = h*pictureRatio + "px";
		view.style.top = 0 + "px";
		view.style.left = w/2-view.width/2 + "px";
		view.height = h;
		view.width = h*pictureRatio;
	}
}*/

/* Main Background */
var bgImage;
function initResize() {
	bgImage = $('#bg');
	if(bgImage.size() > 0) {
		bgImage.get().width = bgImage.get().clientWidth;
		bgImage.get().height = bgImage.get().clientHeight;
		//if(bgImageLoaded)
		{
		  initBg();
		  setTimeout("initBg()", 10);
		}
	}
}
function initBg() {
  var bgImage = $('#bg');
	var sW = document.documentElement.offsetWidth;
	var sH = document.documentElement.offsetHeight;
	var pW = bgImage.width();
	var pH = bgImage.height();
	var pictureRatio = pW/pH;
	var screenRatio = sW/sH;
	
	if(screenRatio > pictureRatio) {
		bgImage.css('width', sW + "px");
		bgImage.css('height', sW/pictureRatio + "px");
		bgImage.css('left', 0 + "px");
		bgImage.css('top', (sH - pH)/2 + "px");
		//bgImage.width() = w;
		//bgImage.height() = w/pictureRatio;
	}
	else {
		bgImage.css('height', sH + "px");
		bgImage.css('width', sH*pictureRatio + "px");
		bgImage.css('top', 0 + "px");
		bgImage.css('left', (sW - pW)/2 + "px");
		//bgImage.height = h;
		//bgImage.width = h*pictureRatio;
	}
}

function HackIssues()
{
  $('span[id*=IssueTitle] ~ br').remove();
  $('span[id*=IssueTitle]').remove();
}

function HackNewsPage()
{
  $('table[id*=ExtrasTable] table[cellpadding=3]').attr('align','right').attr('width','');
  $('table[id*=ExtrasTable] table[cellpadding=3] td').attr('align','center').css('width','auto');
  $('table[id*=ExtrasTable] table[cellpadding=3] td font ~ br').remove();
  $('table[id*=SocialTagsTable]').css('width','130px');
  var DocID = jQuery.url.param('DocumentID');
  if(DocID == "154117"
    || DocID == "174494"
    || DocID == "139637"
    || DocID == "175622")
  {
      $('table[id*=ExtrasTable]').remove();
      $('table[id*=SocialTagsTable]').remove();
  }
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_validateForm() { //v4.0
	var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
	for (i=0; i<(args.length-2); i+=3)
	{
	  test=args[i+2];
	  var val=MM_findObj(args[i]);
	  if (val)
	  {
	    nm=args[i+1];
	    if ((val=val.value)!="" && !/ Name/.test(val))
	    {
        if (test.indexOf('isEmail')!=-1)
        {
          p=val.match(/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/gi);
          if (p==null)
            errors+='- '+nm+' must be a valid e-mail address.\n';
	      }
	      else if (test!='R')
	      {
	        num = parseFloat(val);
	        if (isNaN(val))
	          errors+='- '+nm+' must contain a number.\n';
	        if (test.indexOf('inRange') != -1)
	        {
	          p=test.indexOf(':');
	          min=test.substring(8,p);
	          max=test.substring(p+1);
	          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
	        }
	      }
	    }
	    else if (test.charAt(0) == 'R' || val == 'Name')
	      errors += '- '+nm+' is required.\n';
	  }
	}
	if (errors)
	  alert('The following error(s) occurred:\n'+errors);
	document.MM_returnValue = (errors == '');
}


// JavaScript External Link Exit Message
function exitMsg(){
  var answer = confirm("You are now leaving the Resources Committee website. Thank you for visiting. Neither this office nor the U.S. House of Representatives is responsible for the content of the non-House site you are about to access.")
  if (!answer)
  return false;
  return true;
}


// Check whether links are external:
// (Only works with elements that have href):
$.extend($.expr[':'],{
  external: function(a,i,m) {
    if(!a.href) {return false;}
    if(a.href=='http://twitter.com/NatResourcesGOP') {return false;}
    if(a.href=='http://www.youtube.com/user/NaturalResourcesGOP') {return false;}
    if(a.href=='http://www.facebook.com/home.php#/pages/Committee-on-Natural-Resources-Republicans/75323525339') {return false;}
    if(a.hostname.search(/house\.gov/gi)!=-1) {return false;}
    if(a.hostname.search(/resources\.edgeboss\.net/gi)!=-1) {return false;}
    if(a.href.search(/naturalresourcesgop/gi)!=-1) {return false;}
    if(/facebook\.com\/sharer.php/i.test(a.href)) {return false;}
    return a.hostname && a.hostname !== window.location.hostname;
  }
});

function inputSupportsPlaceholder() {
  var i = document.createElement('input');
  return 'placeholder' in i;
}

function WirePlaceholders(){
  if (!inputSupportsPlaceholder()) {
    $('input[placeholder]').each(function () {
      var textBox = $(this);
      if (textBox.val() == '')
      { textBox.val(textBox.attr('placeholder')); }
      textBox.focus(function () {
        if (textBox.val() == textBox.attr('placeholder'))
        { textBox.val(''); }
      });
      textBox.blur(function () {
        if (textBox.val() == '')
        { textBox.val(textBox.attr('placeholder')); }
      });
      textBox.parents('form').submit(function(){
        if (textBox.val() == textBox.attr('placeholder'))
        { textBox.val(''); }
      });
    });
  }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
  d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
  if (val) { nm=args[i+1]; if ((val=val.value)!="") {
    if (test.indexOf('isEmail')!=-1) { p=val.match(/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/gi);
      if (p==null) errors+='- '+nm+' must be a valid e-mail address.\n';
  } else if (test!='R') { num = parseFloat(val);
  if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
  if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
  min=test.substring(8,p); max=test.substring(p+1);
  if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
  } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}
function f(o)
{
	o.value=o.value.replace(/([^0-9])/g,"");
}

