// page init
$(function(){
	initDropDown();
	initGallery();
	WirePlaceholders();
	internalSidebar();
	SeedFilterBar();
	FormToAkamaiRedirect('appropriations.house.gov');
	PopupControl('popup','#modalPopup',[1,2]);
//	$('#org-name-row').hide();
//	$('#orgType').bind('blur change focus', function(){
//	  $('#org-name-row').toggle($('#org-Type').val() != '' && $('#orgType').val() != 'Personal');
//	});
});

var SubcommitteeMap = 
{
  agricultureruralfda: 43419,
  commercejusticescience: 34794,
  defense: 34795,
  energywater: 34796,
  financegovernment: 34780,
  homelandsecurity: 34797,
  interiorenvironment: 34778,
  laborhealtheducation: 34777,
  legislativebranch: 34776,
  militaryveterans: 35986,
  stateforeignops: 34774,
  transportationhud: 34798
};

function SeedFilterBar()
{
  if($('form.form-filter').size() > 0)
  {
    var params = $.url().param();
    for(index in params)
    {
      if(params[index] != '') {
        $('.form-filter :input[name='+index+']').val(params[index]);
      }
    }
  }
}

function internalSidebar()
{
  var issueId;
  var issueIdMatch = /ID=(\d{5})/.exec($.url().attr('query'));
  if(issueIdMatch)
  {
    issueId = issueIdMatch[1];
  }
  if(!issueId)
  {
    var issueText = $.url().attr('file');
    issueText = issueText.substr(0, issueText.indexOf('.'));
    issueId = SubcommitteeMap[issueText.toLowerCase()];
  }
  $('#menu > li > a[href$='+issueId+']').parent().addClass('active');
  $('#menu > li').each(function(){
    var subcomItem = $(this);
    subcomItem.children('a').each(function(){
      var subcomLink = $(this);
      subcomLink.click(function(){
        if(!subcomItem.hasClass('active'))
        {
          $('#menu > li').removeClass('active');
          subcomItem.addClass('active');
          return false;
        }
      });
    });
  });
}

// init drop-down
function initDropDown(){
	var nav = document.getElementById("nav");
	if (nav){
		var nodes = nav.getElementsByTagName("li");
		for (var i = 0; i < nodes.length; i++){
			if (nodes[i].parentNode.id == "nav"){
				nodes[i].onmouseover = function (){
					this.className += " hover";
					if(this.getElementsByTagName("ul")[0]){
						hideSelectBoxes(this.getElementsByTagName("div")[0]);
					}
				}
				nodes[i].onmouseout = function (){
					this.className = this.className.replace(" hover", "");
					if(this.getElementsByTagName("ul")[0]){
						showSelectBoxes(this.getElementsByTagName("div")[0]);
					}
				}
			}
		}
	}
}

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(''); }
      });
    });
  }
}


// hide select
function hideSelectBoxes(object)
{
	if (!object) return;
	if (!object.sboxes)
		object.sboxes = [];
	var ol = getElementX(object);
	var ot = getElementY(object);
	var ow = object.offsetWidth;
	var oh = object.offsetHeight;
	if ($.browser.msie && ($.browser.version < 7)){
		var sboxes = document.all.tags("select");
		for (var i=0; i<sboxes.length; i++){
			var node = sboxes[i].parentNode;
			while (node != object && node.tagName != "BODY")
				node = node.parentNode;
			var skip = (node == object);
			if (skip) continue;
			var t = getElementY(sboxes[i]);
			var l = getElementX(sboxes[i]);
			var w = sboxes[i].offsetWidth;
			var h = sboxes[i].offsetHeight;
			var ver = false;
			if (t > ot && t < (ot + oh))
				ver = true;
			else if ((t + h) > ot && (t + h) < (ot + oh))
				ver = true;
			var hor = false;
			if (l > ol && l < (ol + ow))
				hor = true;
			else if ((l + w) > ol && (l + w) < (ol + ow))
				hor = true;
			else if (l < ol && (l + w) > ol)
				hor = true;
			if (ver && hor && sboxes[i].style.visibility != "hidden")
				object.sboxes[object.sboxes.length] = sboxes[i];
		}
		for (var i=0; i<object.sboxes.length; i++)
			object.sboxes[i].style.visibility = "hidden";
	}
}

function showSelectBoxes(object)
{
	if (!object) return;
	if (!object.sboxes) return;
	for (var i=0; i<object.sboxes.length; i++)
		object.sboxes[i].style.visibility = "";
	object.sboxes = [];
}

function getElementX(object) {return getElementC(object, true)}
function getElementY(object) {return getElementC(object, false)}

function getElementC(element, xAxis)
{
	var initialElement = element;
	var c = 0;

	while (element != null)
	{
		c += (xAxis) ? element.offsetLeft : element.offsetTop;
		if (element.style.position == "absolute")
			break;
		else
			element = element.offsetParent;
	}

	var elementWnd = document.window;
	if (!elementWnd) return c;

	if (!elementWnd.frameElement) return c;

	return c + getElementC(elementWnd.frameElement, xAxis);
}


function initGallery(){
	$('div.box-slide-show').fadeGalleryAuto({
		slides: '.photo > ul >li',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		switcherHold: 'div.frame',
		autoRotation: true,
		numSlide: true,
		numCurrent: '.current',
		numSumSlide: '.sum-slide',
		switchTime: 4000,
		speed: ($.browser.msie && $.browser.version < 9)? 0 : 650
	});
}
jQuery.fn.fadeGalleryAuto = function(options){
	var options = jQuery.extend({
		hold: '.slide-hold >ul',
		slides: '.slide-hold ul >li',
		btnPrev:'a.btn-prev',
		btnNext:'a.btn-next',
		activeClass: 'active',
		switcherHold: '.carusel .hold',
		switherSlider:'>ul',
		switcher:'> li',
		eventSwitcher:'click',
		pauseOnHover: false,
		numSlide: false,
		numCurrent: '.current',
		numSumSlide: '.sum-slide',
		autoRotation: false,
		autoHeight: false,
		speed: 650,
		swSpeed: 700,
		switchTime: 5000
	}, options);
	
	return this.each(function(){
		var wrapp = jQuery(this);
		var hold = jQuery(options.hold, wrapp);
		var slides = jQuery(options.slides, wrapp);
		var btnPrev = jQuery(options.btnPrev, wrapp);
		var btnNext = jQuery(options.btnNext, wrapp);
		var switcherHold = jQuery(options.switcherHold, wrapp);
		var switherSlider = jQuery(options.switherSlider, switcherHold);
		var switcher = jQuery(options.switcher, switherSlider);
		var eventSwitcher = options.eventSwitcher;
		var activeClass = options.activeClass;
		var pauseOnHover = options.pauseOnHover;
		var numSlide = options.numSlide;
		var numCurrent = jQuery(options.numCurrent, wrapp);
		var numSumSlide = jQuery(options.numSumSlide, wrapp);
		var autoRotation = options.autoRotation;
		var autoHeight = options.autoHeight;
		var switchTime = options.switchTime;
		var speed = options.speed;
		var swSpeed = options.swSpeed;
		
		var current = 0,
			allWidth = 0,
			swSpeedInit = 0,
			switcherWidth = switcherHold.width(),
			swWidth = switcherWidth,
			timer;
		
		slides.hide();
		slides.eq(0).show();
		switcher.eq(0).addClass(activeClass);
		
		if(autoHeight){hold.css({height: slides.eq(0).outerHeight()});}
		
		slides.each(function(ind){
			var slide = $(this);
			if(slide.hasClass(activeClass)){
				slides.hide();
				slide.show();
				switcher.removeClass(activeClass);
				switcher.eq(ind).addClass(activeClass);
				current = ind;
			}
		})
		switcher.each(function(){
			var btn = $(this);
			btn.bind(eventSwitcher, function(){
				if(btn.hasClass(activeClass)){
					if(autoRotation){
						setTimeout(galRotation, speed);
					}
				}else{
					current = btn.index();
					if(!slides.is(':animated')){
						slide();
					}
				}
				return false;
			})
		})
		
		btnPrev.click(function(){
			prevSlide();
			return false;
		})
		btnNext.click(function(){
			nextSlide();
			return false;
		})
		
		function nextSlide(){
			if(current < slides.length - 1){
				current++;
			}else{current = 0}
			if(timer){clearInterval(timer)};
			slide();
			swSlideNext();
		}
		
		function prevSlide(){
			if(current > 0){
				current--;
			}else{
				current = slides.length - 1
			}
			if(timer){clearInterval(timer)};
			slide();
			swSlidePrev();
		}
		
		function slide(){
			switcher.removeClass(activeClass);
			switcher.eq(current).addClass(activeClass);
			slides.fadeOut(speed);
			slides.eq(current).fadeIn(speed, function(){
				galRotation();
			});
			if(autoHeight){
				hold.animate({height: slides.eq(current).outerHeight()}, {queue:false, duration: speed});
			}
			numSumCurrent();
		}
		
		switcher.each(function(){allWidth += $(this).outerWidth(true);})
		
		if(current > 0){swWidth = switcher.eq(current).position().left;}
		
		function swSlideNext(swSpeed){
			var widtnElements = 0,
				mLeft = 0;
			switcher.each(function(){
				var btn = $(this);
				widtnElements += btn.outerWidth(true);
				if(btn.hasClass(activeClass)){
					if(widtnElements > swWidth){
						mLeft = widtnElements - btn.outerWidth(true);
						swWidth += switcherWidth;
						if(switcherWidth > allWidth - mLeft){
							swWidth = allWidth;
							mLeft -= switcherWidth - (allWidth - mLeft);
						}
						switherSlider.animate({marginLeft: -mLeft}, {duration: swSpeed});
					}else if(current == 0){
						swWidth = switcherWidth;
						switherSlider.animate({marginLeft: 0}, {duration: swSpeed});
					}
				}
			})
		}
		function swSlidePrev(){
			var widtnElements = 0,
				mLeft = 0;
			switcher.each(function(){
				var btn = $(this);
				widtnElements += btn.outerWidth(true);
				if(btn.hasClass(activeClass)){
					if(widtnElements <= (swWidth - switcherWidth)){
						mLeft = widtnElements - switcherWidth;
						swWidth -= switcherWidth;
						if(widtnElements < switcherWidth){
							mLeft = 0;
							swWidth = switcherWidth;
						}
						switherSlider.animate({marginLeft: -mLeft}, {duration: swSpeed});
					}else if(current == slides.length - 1 && widtnElements > switcherWidth){
						swWidth = allWidth;
						mLeft = allWidth -switcherWidth;
						switherSlider.animate({marginLeft: -mLeft}, {duration: swSpeed});
					}
				}
			})
		}
		
		function numSumCurrent(){
			if(numSlide){
				numCurrent.html(current + 1);
				numSumSlide.html(slides.length);
			}
		}
		
		if(pauseOnHover){
			wrapp.hover(function(){
				if(timer){clearInterval(timer)};
			}, function(){
				rotation();
			})
		}
		
		function galRotation(){
			clearInterval(timer);
			if(autoRotation){
				timer = setInterval(nextSlide, switchTime);
			}
		}
		
		swSlideNext(swSpeedInit);
		numSumCurrent();
		galRotation();
	});
};
// Send relative links to unSSL canonical DNS
function FormToAkamaiRedirect(defaultDomain)
{
  if(location.hostname != defaultDomain
    || location.protocol != 'http:')
  {
    $('a[href^=\\/]').each(function(){
      var origUrl = $(this).attr('href');
      $(this).attr('href', 'http://' + defaultDomain + origUrl);
    });
  }
}
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
// JS Popup port
function PopupControl(cookieName, popupLink, integerArray){
  if($(popupLink).size()>0){
    if(readCookie(cookieName + '-session') != 'true'){
      var visitCount = parseInt(readCookie(cookieName), 10);
      if(isNaN(visitCount)){
        visitCount = 1; }
      for (index = 0; index < integerArray.length; index++){
        if(integerArray[index] == visitCount){
          setTimeout('$("'+popupLink+'").click()',200); }
      }
      createCookie(cookieName + '-session', 'true');
      createCookie(cookieName, visitCount + 1, 365);
    }
  }
}

