// tabs function
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));

					//reset all tabs on start
					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
					    StopAllVideos();
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							//reset all tabs before change
							for (var i = 0; i < this.tabs.length; i++)
							{
								document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1)).style.display = "none";
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}
function WireHtml5(){
  function inputSupportsPlaceholder() {
    var i = document.createElement('input');
    return 'placeholder' in i;
  }
  function inputSupportsRequired() {
    var i = document.createElement('input');
    return 'required' in i;
  }
  function inputSupportsPattern() {
    var i = document.createElement('input');
    return 'pattern' in i;
  }
  function inputSupportsType(inputType) {
    var i = document.createElement('input');
    i.setAttribute('type',inputType);
    return i.type !== 'text';
  }
  var emailRegex = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/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(''); }
        });
      });
    }
  }
  WirePlaceholders();
  function getFieldName(jqEl)
  {
    var msg = jqEl.attr('title');
    if(!msg)
    {
      msg = jqEl.attr('placeholder');
    }
    if(!msg && jqEl.attr('id'))
    {
      msg = $('label[for='+jqEl.attr('id')+']').text();
    }
    if(!msg)
    {
      msg = "A form field";
    }
    return msg;
  }
  function invalidRequiredValue(jqEl)
  {
    return (jqEl.val() == '' ||
          jqEl.val() == null ||
          jqEl.val() == 'null' ||
          jqEl.val() == jqEl.attr('placeholder'));
  }
  $('form select[required] option:not([value])').each(function(){
    var emptyOption = $(this);
    var text = emptyOption.text();
    var select = emptyOption.parent();
    var oldVal = select.val();
    emptyOption.replaceWith('<option value="">'+text+'</option>');
    select.val(oldVal);
  });
  if(!inputSupportsRequired()||!inputSupportsType('email'))
  {
    $('form:has(:input[required]), form:has(:input[type=email])').each(function(){
      var form = $(this);
      form.find(':input[required], input[type=email]').each(function(){
        var textBox = $(this);
        textBox.keyup(function(){
          var validValue = true;
          if(textBox.is('[required]'))
          {
            validValue &= !invalidRequiredValue(textBox);
          }
          if(textBox.is('[type=email]'))
          {
            validValue &= emailRegex.test(textBox.val());
          }
          textBox.toggleClass('error', !validValue);
        });
      });
      form.submit(function(){
        var errorPopupText = 'Form submission errors:\n';
        var errorCount = 0;
        form.find(':input[required]').each(function(i){
          var textBox = $(this);
          var msg = getFieldName(textBox);
          if (invalidRequiredValue(textBox) ||
            (textBox.attr('type')=='radio' && form.find('input[name='+textBox.attr('name')+']:checked').val() == null))
          {
            if(errorPopupText.indexOf(msg)<=-1)
            {
              errorPopupText += " - " + msg + ' is required.\n';
            }
            textBox.addClass('error');
            errorCount++;
          }
        });
        form.find('input[type=email]').each(function(i){
          var textBox = $(this);
          var msg = getFieldName(textBox);
          if (!invalidRequiredValue(textBox) && !emailRegex.test(textBox.val()))
          {
            if(errorPopupText.indexOf(msg)<=-1)
            {
              errorPopupText += " - " + msg + ' must be a valid email address.\n';
            }
            textBox.addClass('error');
            errorCount++;
          }
        });
        if(errorCount>0)
        {
          alert(errorPopupText);
          return false;
        }
      });
    });
  }
}
function valDrop(val) {
if (val == '') return false;
else return true;
}
function StopMediaRotation(){
  $('.media-area').cycle('pause');
}
function RandomBanner(selector)
{
  var list = $(selector);
  list.hide().eq(Math.floor(Math.random()*list.length)).show();
}

// init background rotation gallery
function initGallery() {
	// init header background rotator
//	$('.bg-list').cycle({
//	  timeout:5000,
//	  speed:1000
//	});
  RandomBanner('.bg-list li');

	// init media gallery
	$('.gallery').each(function(){
	  var _gallery = $(this);
	  _gallery.cycle({
	    slideExpr:'.img-holder > li',
	    timeout:6000,
	    speed:600,
	    next:_gallery.find('a.next'),
	    prev:_gallery.find('a.prev'),
	    pager:_gallery.find('.slide-list'),
	    pagerAnchorBuilder:function(index){
	      return '<li><a href="#">'+(index+1)+'</a></li>';
	    },
	    activePagerClass:'active',
	    before: StopAllVideos,
	    onPagerEvent:StopMediaRotation,
	    onPrevNextEvent:StopMediaRotation,
	    cleartypeNoBg:true
	  });
	});
	
	//init media tabs (auto-advance)
	$('.media-area').each(function(){
	  var _tabHolder = $(this);
		var _tabset = jQuery('ul.tabset li', this).remove();
	  _tabHolder.cycle({
	    slideExpr:'.tabs-content > div',
	    timeout:0,
	    speed:200,
	    startingSlide:1,
	    pager:_tabHolder.find('ul.tabset'),
	    pagerAnchorBuilder:function(index){
	      return _tabset[index];
	    },
	    activePagerClass:'active',
	    before: StopAllVideos,
	    onPagerEvent:StopMediaRotation,
	    cleartypeNoBg:true
	  });
	});
	
	
	//init In The News tabs
	$('.news-area').each(function(){
	  var _tabHolder = $(this);
		var _tabset = $('ul.tabset li', this);
		var _tabs = $('.news-content > .tab', this);
	  //var _activeSlide = _tabset.index(_tabset.filter('active'));
	  var _activeSlide = parseInt($('#NewsStartTab').val(),10);
	  _tabs.filter(':not(:eq('+_activeSlide+'))').hide();
	  _tabset.each(function(){
	    var _switchLink = $(this);
	    _switchLink.click(function(){
	      _tabset.removeClass('active');
	      _switchLink.addClass('active');
	      _tabs.hide();
	      _tabs.eq(_tabset.index(_switchLink)).show();
	    });
	  });
	});
}

// resizable fonts control area
function initPageResize () {
	var fMin = document.getElementById("font-small");
	var fNormal = document.getElementById("font-medium");
	var fMax = document.getElementById("font-large");
	var fSize = 62.5;
	if(fMin && fNormal && fMax) {
		var body = document.getElementsByTagName("body")[0];
		body.style.fontSize = "62.5%";
		fMin.onclick = function (){
			fSize = body.style.fontSize.replace("%","");
			fSize = parseInt(fSize) - 10;
			if (fSize <= 50) fSize = 50;
			body.style.fontSize = fSize+"%";
			return false;
		}
		fMax.onclick = function (){
			fSize = body.style.fontSize.replace("%","");
			fSize = parseInt(fSize) + 10;
			if (fSize >= 90) fSize = 90;
			body.style.fontSize = fSize+"%";
			return false;
		}
		fNormal.onclick = function (){
			body.style.fontSize = "62.5%";
			return false;
		}
	}
}

// init page
function initPage () {
	//initTabs();
	//WirePlaceholders();
	WireHtml5();
	initGallery();
	initPageResize();
	FlagPage();
	HackIssues();
	Seeding();
	HackLists();
	$('table[id*=EmailGrid] a[target=_blank]').addClass('middleheadline');
	FormToAkamaiRedirect('hirono.house.gov');
}
if (window.addEventListener) window.addEventListener("load", initPage, false);
else if (window.attachEvent) window.attachEvent("onload", initPage);

function FlagPage()
{
  $('#FlagOrderBox tr:gt(0):not(:last)').each(function(){
    var currentRow = $(this);
    CalcFlagRow(currentRow);
  });
  $('#FlagOrderBox tr:gt(0):not(:last)').each(function(){
    var currentRow = $(this);
    currentRow.find('input').change(function(){
        CalcFlagRow(currentRow);
    });
  });
}

function HackIssues()
{
  $('#icontent .pageTitle[id*=IssueTitle] ~ br').remove();
  $('#icontent .pageTitle[id*=IssueTitle]').remove();    
}

function CalcFlagTotals()
{
  var totalFlags = 0;
  var totalPrice = 0;
  $('#FlagOrderBox tr:gt(0):not(:last)').each(function(){
    var rowFlags = parseInt($(this).find('input:text').val(),10);
    var rowPrice = parseFloat($(this).children('td:last').html().replace(/\$/g,''),10);
    if(!isNaN(rowFlags))
    {
      totalFlags += rowFlags;
    }
    if(!isNaN(rowPrice))
    {
      totalPrice += rowPrice;
    }
  });
  $('#FlagOrderBox tr:last td:first').html(totalFlags);
  $('#FlagOrderBox tr:last th:last').html('$' + totalPrice.toFixed(2).toString());
}

function CalcFlagRow(currentRow)
{
  var flagPrice = parseFloat(currentRow.find('input:hidden').val());
  if(currentRow.find('input:checkbox').is(':checked'))
  {
    flagPrice += 4.05;
  }
  var numFlags = parseInt(currentRow.find('input:text').val(),10);
  if(isNaN(numFlags))
  {
    numFlags = 0;
  }
  if(numFlags > 0)
  {
    currentRow.children('td:last').html('$' + (numFlags*flagPrice).toFixed(2).toString());
  }
  else
  {
    currentRow.children('td:last').html('');
  }
  CalcFlagTotals();
}

/* --- Seed Contact with Zips & Email Signup with Name/Addy --- */
function Seeding()
{
  var formID = $.url().param('ID');
  if(formID == '398')
  {
    SeedHelper('email', $('input[id$=EmailControl]'));
  }
}
function SeedHelper (parameterString, targetInput)
{
  var param = $.url().param(parameterString);
  if(param!=null)
  {
    param = unescape(param.replace(/\+/g, ' '));
    targetInput.val(param);
  }
}

function HackLists()
{
  $('.ContentCell span.middlecopy > ul:last-child').css('margin-bottom','0');
}

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById(playerId);
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
  //alert("Player's new state: " + newState);
  if(newState == 1)
  {
    $('div.gallery').cycle('pause');
  }
  else if(newState == 2 || newState == 0)
  {
    $('div.gallery').cycle('resume');
  }
}

function StopAllVideos()
{
  var video = $('object[id*=ytplay], embed[id*=ytplay]');
  video.each(function(){
    try{
      this.stopVideo();
    }
    catch(err)
    {
      //var vidError = err;
      //var nothing = 6;
    }
  });
}
function f(o)
{
	o.value=o.value.replace(/([^0-9])/g,"");
}
var state = "HI";
var district = "02";

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 == '');
}
// 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);
    });
  }
}

