$(document).ready(function(){
	$('div.slide-show').gallery({
		duration: 500,
		autoRotation: 5000,
		listOfSlides: '.slide > li',
		switcher: '.switcher>li',
		effect:true,
		IE:true
	});
	randomImg();
	WirePlaceholders();
	Seeding();
	FormToAkamaiRedirect('mikerogers.house.gov');
});
function randomImg(){
	var holder = $('.banner');
	var activeClass = 'active';
	holder.each(function(){
		els = $(this).find('li');
		els.eq(Math.floor(Math.random() * (els.length))).addClass(activeClass);
	});
}
(function($) {
	$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };
	
	function Gallery(context, options) { this.init(context, options); };
	
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				duration: 700,
				slideElement: 1,
				autoRotation: false,
				effect: false,
				listOfSlides: 'ul > li',
				switcher: false,
				disableBtn: false,
				nextBtn: 'a.link-next, a.btn-next, a.next',
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',
				circle: true,
				direction: false,
				event: 'click',
				IE: false
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			if (this.options.switcher) this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
			
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			
			this.woh = _el.outerWidth(true);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
			
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				if (!this.options.direction) this.list.css({marginLeft: -(this.woh * this.active)});
				else this.list.css({marginTop: -(this.woh * this.active)});
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			}
			
			if (this.options.disableBtn) {
				if (this.count < this.wrapHolderW) this.nextBtn.addClass(this.options.disableBtn);
				if (this.active == 0) this.prevBtn.addClass(this.options.disableBtn);
			}
			
			this.initEvent(this, this.nextBtn, this.prevBtn, true);
			this.initEvent(this, this.prevBtn, this.nextBtn, false);
			
			if (this.options.autoRotation) this.runTimer(this);
			
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.floor(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderWwrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && $.browser.version == '6.0' && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function(){
			if (!this.options.direction) this.list.animate({marginLeft: -(this.woh * this.active)}, {queue:false, duration: this.options.duration});
			else this.list.animate({marginTop: -(this.woh * this.active)}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this));
				if($this._t) clearTimeout($this._t);
				if (!$this.options.effect) $this.scrollElement();
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, addDisClass, dir){
			addEventEl.bind($this.options.event, function(){
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) addDisClass.removeClass($this.options.disableBtn);
				$this.toPrepare($this, dir);
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		toPrepare: function($this, side){
			if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
			if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
			for (var i = 0; i < $this.options.slideElement; i++){
				if (side) {
					if ($this.active + 1 > $this.rew) {
						if ($this.options.disableBtn && ($this.count > $this.wrapHolderW)) $this.nextBtn.addClass($this.options.disableBtn);
					}
					else $this.active++;
				}
				else{
					if ($this.active - 1 < 0) {
						if ($this.options.disableBtn && ($this.count > $this.wrapHolderW)) $this.prevBtn.addClass($this.options.disableBtn);
					}
					else $this.active--;
				}
			};
			if ($this.active == $this.rew && side) if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) $this.nextBtn.addClass($this.options.disableBtn);
			if ($this.active == 0 && !side) if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) $this.prevBtn.addClass($this.options.disableBtn);
			if (!$this.options.effect) $this.scrollElement();
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));

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')); }
      });
    });
  }
}

function Seeding()
{
  var formID = $.url().param('ID');
  if(formID == '1004')
  {
    SeedHelper('email', $('input[id*=EmailControl]'));
    SeedHelper('firstname',$('#'+$('label:contains(First Name)').attr('for')));
    SeedHelper('lastname',$('#'+$('label:contains(Last Name)').attr('for')));
  }
}
function SeedHelper (parameterString, targetInput)
{
  var param = $.url().param(parameterString);
  if(param!=null)
  {
    param = unescape(param.replace(/\+/g, ' '));
    targetInput.val(param);
  }
}

function f(o)
{
	o.value=o.value.replace(/([^0-9])/g,"");
}
var state = "MI";
var district = "08";

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 FlagPage()
{
  $('#FlagOrderBox tr:gt(0):not(:last)').each(function(){
      var currentRow = $(this);
      CalcFlagTotals();
  });
  $('#FlagOrderBox tr:gt(0):not(:last)').each(function(){
      var currentRow = $(this);
      currentRow.find('input').bind('change keyup keydown', function(){
          CalcFlagTotals();
      });
  });
  $('#copyInfo').each(function(){
    var copyButton = this;
    $(copyButton).click(function(){
      for (var i=0; i<9; i++) {	  
	      copyButton.form.elements[i+12].value = copyButton.form.elements[i].value;	
		  }  
	    return;
	  });
  });
}

function CalcFlagTotals()
{
  var totalFlags = 0;
  var totalPrice = 0;
  var totalFlown = 0;
  $('#FlagOrderBox tr:gt(0):lt(5)').each(function(){
    var rowFlagsFlown = parseInt($(this).find('input:text:first').val(),10);
    var rowFlagsNotFlown = parseInt($(this).find('input:text:last').val(),10);
    var rowPriceFlown = parseFloat($(this).find('input:hidden:first').val(),10);
    var rowPriceNotFlown = parseFloat($(this).find('input:hidden:last').val(),10);
    var rowPrice = 0;
    if(!isNaN(rowPriceFlown * rowFlagsFlown))
    {
      rowPrice += rowPriceFlown * rowFlagsFlown;
      totalFlown += rowFlagsFlown;
    }
    if(!isNaN(rowPriceNotFlown * rowFlagsNotFlown))
    {
      rowPrice += rowPriceNotFlown * rowFlagsNotFlown;
    }
    if(!isNaN(rowFlagsFlown) && !isNaN(rowFlagsNotFlown))
    {
      totalFlags += rowFlagsFlown + rowFlagsNotFlown;
    }
    if(!isNaN(rowPrice))
    {
      totalPrice += rowPrice;
      $(this).find('td:last').text(rowPrice > 0 ? '$'+rowPrice.toFixed(2) : '');
    }
  });
  $('.flag-info').toggle(totalFlown > 0);
  $('#FlagOrderBox tr:eq(6) th:last').html(totalPrice > 0 ? '$' + totalPrice.toFixed(2).toString() : '');
  $('#FlagOrderBox tr:last th:last').html(totalPrice > 0 ? '$' + (totalPrice + 5.25).toFixed(2).toString() : '');
}
// 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);
    });
  }
}

