function ieHover(){
	$('#menu li').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
}
if (window.attachEvent && !window.opera){
	window.attachEvent("onload", ieHover);
}
function hideCities(){
	$('.maps a').attr('class','');
}

var relurl = $.url().attr('relative').toLowerCase();
var fullurl = $.url().attr('source').toLowerCase();
var relurl = relurl.replace(/&page=\d{0,}/gi,'');
var fullurl = fullurl.replace(/&page=\d{0,}/gi,'');
var helpdeskpage = relurl.match(/helpdesk/gi);
var linkspage = relurl.match(/links/gi);
var photoToShow = 1;
var videoToShow = 1;
var numPhotos;
var numVideos;
$(document).ready(function(){
  FormToAkamaiRedirect('geoffdavis.house.gov');
  // set up welcome vid (BETA)
  if($('#flashwelcome').length > 0)
  {
//	    var so = new SWFObject("/welcome/welcome.swf", "welcome", "410", "263", "8");
//        so.write("flashwelcome");
  }
  // Fix for validation on empty <option/>s
  var opty = $('option:empty:not([value])');
  $('option:empty:not([value])').val('');
  CornersAndStripes();
  HackNewsPage();
  FrameIssues();
  AddExitMsg();
  // remove duplicate headlines on issue pages
  $('#ctl00_ctl06_IssueTitle ~ br').remove();
  $('#ctl00_ctl06_IssueTitle').remove();
  // highlight sidebar current url
  highlightUrl();
  // Remove dropdowns on pages with pdf iFrames
  PdfIframeHack();
  HackLinksWithFS21();
  ValidateForms();
  // Set up TextOnly
  if(readCookie("textonly")=="true")
  {
    $('#Stylesheet1').attr('href','null');
    $('#TextOnly').attr('style','color:Red; font-weight:bold; font-size:1.6em;');
  }
  // Set up popup
  if(readCookie('popup')!='hide')
  {
    $('#modalPopup').click();
    createCookie('popup','hide',700);
  }
  // clear text boxes on click
  SetUpFieldHides();
  //Header clickable
  $('#header .header-box').click(function(){
    window.location = '/';
  });
  //Set up Datepicker
  $('.datepicker').datepicker();
  //Homepage Subtabs
  InitPhotoTab();
  //Set up Photo Album Anchor handlers
  SetUpAnchorHandlers();
  // Seed forms
  Seeding();
	// reset all tabs on start
	$('.tabset').find('a.tab').each(function(){
		if($(this).is('.active')){
			$($(this).attr('href')).show();
			hideCities();
			_rel = $(this).attr('rel');
			if (_rel) {
				$('#'+_rel).addClass(_rel);
			}
		} else {
			$($(this).attr('href')).hide();
		}
	});
	$('.tabset').find('a.tab').click(function(){
	    StopAllVideos();
		$(this).parent().parent().find('a.tab').each(function(){
			$(this).removeClass('active');
			$($(this).attr('href')).hide();
		});
		$(this).addClass('active');
		$($(this).attr('href')).show();
		if(!$(this).parent().parent().hasClass('tabs-top'))
		{
	    hideCities();
		}
		_rel = $(this).attr('rel');
		if (_rel) {
			$('#'+_rel).addClass(_rel);
		}
		return false;
	});
	$('.maps a').click(function(){
    var Gpa = $(this).parent().parent();
    var link = $(this).attr('href');
    Gpa.find('.footer-box-bottom').children('.tab').hide();
    Gpa.find('.tabset a.tab').removeClass('active');
    Gpa.find('.tabset a.tab').each(function(){
      if($(this).attr('href') == link)
      {
        $(this).addClass('active');
      }
    });
    Gpa.find(link).show();
    hideCities();
    $(this).addClass($(this).attr('id'));
	});
});

function CornersAndStripes()
{
  // set sidebar corners
  $('.section-links').corner('14px bottom');
  //$('#sidebar .section-links').corner('14px top');
  $('.doc-search').corner('14px');
  $('.issue-repeater, .survey').corner('14px');
  $('.rsl-border').corner();
  $('.rs-link, .survey-title').corner('8px');
  // Stripe dropdown menus
  $('.drop-down-top li:even a').addClass('color');
}

function FrameIssues()
{
  $('.icons li').each(function(){
    var issueLink = $(this).children('a:first').attr('href');
    $(this).append('<a href="'+issueLink+'" class="icon-frame">&nbsp;</a>');
  });
  $('#issueslist td .isshold').each(function(){
    var issueLink = $(this).children('a:first').attr('href');
    $(this).append('<a href="'+issueLink+'" class="icon-frame-int">&nbsp;</a>');
  });
}

function SetUpFieldHides()
{
  $('input[type="text"]').addClass("idleField");
  $('.embed-txt').removeClass('idleField');
  $('.idleField').focus(function() {  
    $(this).removeClass("idleField").addClass("focusField");  
    if (this.value == this.defaultValue){  
      this.value = '';  
    }  
    if(this.value != this.defaultValue){  
      this.select();  
    }  
  });  
  $('input[type="text"]').blur(function() {  
    $(this).removeClass("focusField").addClass("idleField");  
    $('.embed-txt').removeClass('idleField');
    if ($.trim(this.value) == ''){  
      this.value = (this.defaultValue ? this.defaultValue : '');  
    }  
  });  
}

function highlightUrl()
{
  $('.RightSidebar li a').each(function(){
    var href = $(this).attr('href').toLowerCase();
    if((href == relurl) || (href == fullurl))
    {
      $(this).addClass('red');
    }
    if((href=='/helpdesk/') && (helpdeskpage != -1) && (helpdeskpage != null))
    {
      $(this).addClass('red');
    }
    if((href=='/links/state.htm') && (linkspage != -1) && (linkspage != null))
    {
      $(this).addClass('red');
    }
  });
}

function HackNewsPage()
{
//    if(relurl.match(/news/gi) != null)
//    {
//        $('#ctl00_ctl03_TopStories_ctl04_Table1 ~ p').remove();
//        $('#ctl00_ctl03_TopStories_ctl04_Table1 ~ ul').remove();
//        $('#aspnetForm > .pageTitle:gt(0)').remove();
//        $('#aspnetForm > .pageTitle:first ~ ul').remove();
//        $('#aspnetForm > .pageTitle').removeClass('pageTitle');
//        $('#PageContent .middleheadline > b').addClass('NewsHeadline');
//        $('b.NewsHeadline').click(function(){
//            var linkTo = $(this).parent().parent().children('a:first').attr('href');
//            window.location=linkTo;
//        });
//    }
  $('#PageContent a:not([href])').css('color','#000').css('text-decoration','none');
}

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;
}

function ToggleTextOnly()
{
  if(readCookie("textonly")==null||readCookie("textonly")=="false")
  {
    createCookie("textonly","true");
    $('#Stylesheet1').attr('href','null');
    $('#TextOnly').attr('style','color:Red; font-weight:bold; font-size:1.6em;');
  }
  else
  {
    createCookie("textonly","false");
    $('#Stylesheet1').attr('href','/css/all.css');
    $('#TextOnly').attr('style','');
  }
}

function InitPhotoTab()
{
  numPhotos = $('#homePhotos li').length;
  numVideos = $('#homeVideos li').length;
  $('#homePhotos li:gt(0)').hide();
  $('#homeVideos li:gt(0)').hide();
  $('#homePhotos a').click(function(event){        
    var slide = $(this).attr('rel');
    if(slide == "Prev")
    {
      event.preventDefault();
      if(photoToShow > 1)
      {
        photoToShow--;
      }
      else
      {
        photoToShow = numPhotos;
      }
      $(this).parent().find('.slides li').hide();
      $(this).parent().find('.slides li:eq('+(photoToShow-1)+')').show();
    }
    else if (slide == "Next")
    {
      event.preventDefault();
      if(photoToShow < numPhotos)
      {
        photoToShow++;
      }
      else
      {
        photoToShow = 1;
      }
      $(this).parent().find('.slides li').hide();
      $(this).parent().find('.slides li:eq('+(photoToShow-1)+')').show();
    }
  });
  $('#homeVideos a').click(function(event){
    StopAllVideos();
    var slide = $(this).attr('rel');
    if(slide == "Prev")
    {
      event.preventDefault();
      if(videoToShow > 1)
      {
        videoToShow--;
      }
      else
      {
        videoToShow = numVideos;
      }
      $(this).parent().find('.slides li').hide();
      $(this).parent().find('.slides li:eq('+(videoToShow-1)+')').show();
    }
    else if (slide == "Next")
    {
      event.preventDefault();
      if(videoToShow < numVideos)
      {
        videoToShow++;
      }
      else
      {
        videoToShow = 1;
      }
      $(this).parent().find('.slides li').hide();
      $(this).parent().find('.slides li:eq('+(videoToShow-1)+')').show();
    }
  });
}


// Handler for anchors
/*
  jQuery anchor handler - 0.5
  http://code.google.com/p/jquery-utils/

  (c) Maxime Haineault <haineault@gmail.com>
  http://haineault.com   

  MIT License (http://www.opensource.org/licenses/mit-license.php)

*/

(function($){
  var hash = window.location.hash;
  var handlers  = [];
  var opt = {};

  $.extend({
    anchorHandler: {
      apply: function() {
        $.map(handlers, function(handler){
          var match = hash.match(handler.r) && hash.match(handler.r)[0] || false;
          if (match)  { handler.cb.apply($('a[href*='+match+']').get(0), [handler.r, hash || '']); }
        });
        return $.anchorHandler;
      },
      add: function(regexp, callback, options) {
        var opt  = $.extend({handleClick: true, preserveHash: true}, options);
        if (opt.handleClick) { 
          $('a[href*=#]').each(function(i, a){
            if (a.href.match(regexp)) {
              $(a).bind('click.anchorHandler', function(){
                if (opt.preserveHash) { window.location.hash = a.hash; }
                return callback.apply(this, [regexp, a.href]);
              });
            }
          }); 
        }
        handlers.push({r: regexp, cb: callback});
        $($.anchorHandler.apply);
        return $.anchorHandler;
      }
    }
  });
})(jQuery);


function SetUpAnchorHandlers(){
  $('.PhotoAlbumTitle').each(function(){
    var albumAnchor = $(this).attr('id');
    var albumID = albumAnchor.match(/\d+/);
    $.anchorHandler.add('oto', function(){$(this).show();});
    var nothing = 5;
    //$(this).hide();
  });
}

function PdfIframeHack()
{
  $('iframe[src*=.pdf]').each(function(){
    $('#menu .drop-down-top').remove();
  });
  if(relurl.match(/multimedia/) != null)
  {
    $('#menu .drop-down-top').remove();
  }
}

function ValidateForms()
{
//    $('form.valForm input').validate({
//        rules:{
//            zip5:{required:true}
//        },
//        messages: {
//            required:'',
//            email:'<br/>Please enter a valid email address',
//            zip5:'arg!'
//        }
//    });
//    
    
  $('form.valForm').validate({
    //debug:true,
    errorContainer: "#ErrorHeader, #ErrorList",
    errorLabelContainer: "#ErrorList"
    //wrapper: "span"
    //messages:{zip5:'argle'}
  });
}

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 HackLinksWithFS21()
{
  //alert('hi');
  $('a[href*=fireside21]').each(function(){
    //alert('hi2');
    var templink = $(this).attr('href');
    templink = templink.replace(/davis\.fireside21\./gi,'geoffdavis.');
    $(this).attr('href',templink);
  });
  $('#PageContent [style*="ms sans serif"]').css('font-family','Helvetica, Verdana, Tahoma, Arial, Sans-Serif');
}

function Seeding()
{
  var formID = $.url().param('ID');
  if(formID == '480') // Teletown Hall Form
  {
    // Prefix
    var pfxBox = $('#' + $('label:contains(Prefix)').attr('for'));
    var pfxId = pfxBox.attr('id');
    var pfxName = pfxBox.attr('name');
    var pfxSelect = $('<select></select>');
    pfxSelect.attr('id', pfxId);
    pfxSelect.attr('name', pfxName);
    pfxSelect.append('<option value=""></option><option value="Ms.">Ms.</option><option value="Mr.">Mr.</option><option value="Mrs.">Mrs.</option><option value="Dr.">Dr.</option>');
    pfxBox.replaceWith(pfxSelect);
    
    // Restrict Home & Business state to Kentucky
    $('select[id*=AddressState]').html('<option value="KY">Kentucky</option>');
    
    // Home Address required fields
    $('.formFieldContainer:contains(Home) .formAddress label:not(:eq(1))').append(' *');
    
    // Bind Home Address Zip to call the zip validation function
    $('input[id*=AddressZip]').blur(function(){
      xajax_getTTHcode(
        $('.formFieldContainer:contains(Home) input[id$=AddressZip]').val(),
        $('.formFieldContainer:contains(Home) input[id$=Plus4]').val(),
        state,
        district,
        $('label:contains(Find your zip)').attr('for'));
    });
    
    // Hide the Zip Validation box
    $('#' + $('label:contains(Find your zip)').attr('for')).hide();
  }
  else if (formID == '482')
  {
    $('.formAddress label:not(:eq(1))').append(' *');
  }
  $('form#paramform').append($('#form-info').remove());
}

// JavaScript External Link Exit Message
function exitMsg(){
  var answer = confirm("You are now leaving the website of Congressman Geoff Davis. Thank you for visiting. Neither Congressman Geoff Davis 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.hostname.search(/house\.gov/gi)!=-1) {return false;}
    if(a.href.search(/user\/congressmandavis/gi)!=-1) {return false;}
    return a.hostname && a.hostname !== window.location.hostname;
  }
});

/* --- Add Exit Message ---*/
function AddExitMsg()
{
  $('a:external').click(function(){
    return(exitMsg());
  });
}
// 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);
    });
  }
}

