
$(document).ready(function(){
	
	$('html').removeClass('js');
	
	$("#tabs").superfish({
		delay: 1000 
	}).find('ul').bgIframe();
	
	$("#ins-type").selectbox();
	$("#frm-zip label").addClass('infield');
	$("#frm-zip .infield").inFieldLabels();
	var d = new Date();
	$(".date").datepicker({ changeYear: true,  yearRange: '1900:'+d.getFullYear() });
	
});

// Js form error highlighting
function restore_form_vals(fields){
	for(field in fields){
		$('#'+field).val( fields[field] );
	}
}

// Js form error highlighting
function highlight_errors(fields){
	fields = $.evalJSON(fields);
	$('span.invalid').remove();
	if(fields.length){
		for(x in fields){
			$('#'+fields[x]).css('border-color', 'red').after('<span class="invalid"> *</span>');
			$('span.invalid').css('color', 'red');
		}
		$('form').before('<p class="error">There were missing or invalid fields. Please ensure that all fields have been filled out.</p>');
	}
}


/**
* hoverIntent r5 - http://cherne.net/brian/resources/jquery.hoverIntent.html
*/
;(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/*
 * bgIframe - v2.1.2-pre - http://brandonaaron.net - Copyright (c) 2008 Brandon Aaron
 */
;(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:"auto",left:"auto",width:"auto",height:"auto",opacity:true,src:"javascript:false;"},s||{});var prop=function(n){return n&&n.constructor==Number?n+"px":n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?"filter:Alpha(Opacity='0');":"")+"top:"+(s.top=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+'px')":prop(s.top))+";left:"+(s.left=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+'px')":prop(s.left))+";width:"+(s.width=="auto"?"expression(this.parentNode.offsetWidth+'px')":prop(s.width))+";height:"+(s.height=="auto"?"expression(this.parentNode.offsetHeight+'px')":prop(s.height))+';"/>';return this.each(function(){if($("> iframe.bgiframe",this).length==0){this.insertBefore(document.createElement(html),this.firstChild);}});}return this;};})(jQuery);

/*
 * Superfish - v1.4.8 - http://users.tpg.com.au/j_birch/plugins/superfish - Copyright (c) 2008 Joel Birch
 */
;(function($){$.fn.superfish=function(op){var sf=$.fn.superfish,c=sf.c,$arrow=$(['<span class="',c.arrowClass,'"> &#187;</span>'].join("")),over=function(){var $$=$(this),menu=getMenu($$);clearTimeout(menu.sfTimer);$$.showSuperfishUl().siblings().hideSuperfishUl()},out=function(){var $$=$(this),menu=getMenu($$),o=sf.op;clearTimeout(menu.sfTimer);menu.sfTimer=setTimeout(function(){o.retainPath=($.inArray($$[0],o.$path)>-1);$$.hideSuperfishUl();if(o.$path.length&&$$.parents(["li.",o.hoverClass].join("")).length<1){over.call(o.$path)}},o.delay)},getMenu=function($menu){var menu=$menu.parents(["ul.",c.menuClass,":first"].join(""))[0];sf.op=sf.o[menu.serial];return menu},addArrow=function($a){$a.addClass(c.anchorClass).append($arrow.clone())};return this.each(function(){var s=this.serial=sf.o.length;var o=$.extend({},sf.defaults,op);o.$path=$("li."+o.pathClass,this).slice(0,o.pathLevels).each(function(){$(this).addClass([o.hoverClass,c.bcClass].join(" ")).filter("li:has(ul)").removeClass(o.pathClass)});sf.o[s]=sf.op=o;$("li:has(ul)",this)[($.fn.hoverIntent&&!o.disableHI)?"hoverIntent":"hover"](over,out).each(function(){if(o.autoArrows){addArrow($(">a:first-child",this))}}).not("."+c.bcClass).hideSuperfishUl();var $a=$("a",this);$a.each(function(i){var $li=$a.eq(i).parents("li");$a.eq(i).focus(function(){over.call($li)}).blur(function(){out.call($li)})});o.onInit.call(this)}).each(function(){var menuClasses=[c.menuClass];if(sf.op.dropShadows&&!($.browser.msie&&$.browser.version<7)){menuClasses.push(c.shadowClass)}$(this).addClass(menuClasses.join(" "))})};var sf=$.fn.superfish;sf.o=[];sf.op={};sf.IE7fix=function(){var o=sf.op;if($.browser.msie&&$.browser.version>6&&o.dropShadows&&o.animation.opacity!=undefined){this.toggleClass(sf.c.shadowClass+"-off")}};sf.c={bcClass:"menu-at",menuClass:"sf-js-enabled",anchorClass:"menu-with-ul",arrowClass:"menu-sub-indicator",shadowClass:"menu-shadow"};sf.defaults={hoverClass:"menu-live",pathClass:"at",pathLevels:1,delay:1000,animation:{opacity:"show"},speed:"normal",autoArrows:false,dropShadows:false,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};$.fn.extend({hideSuperfishUl:function(){var o=sf.op,not=(o.retainPath===true)?o.$path:"";o.retainPath=false;var $ul=$(["li.",o.hoverClass].join(""),this).add(this).not(not).removeClass(o.hoverClass).find(">ul").hide().css("visibility","hidden");o.onHide.call($ul);return this},showSuperfishUl:function(){var o=sf.op,sh=sf.c.shadowClass+"-off",$ul=this.addClass(o.hoverClass).find(">ul:hidden").css("visibility","visible");sf.IE7fix.call($ul);o.onBeforeShow.call($ul);$ul.animate(o.animation,o.speed,function(){sf.IE7fix.call($ul);o.onShow.call($ul)});return this}})})(jQuery);

/*
 * In-Field Label - v0.1 - http://fuelyourcoding.com/scripts/infield.html - Copyright (c) 2009 Doug Neiner
 */
;(function($){$.InFieldLabels=function(b,c,d){var f=this;f.$label=$(b);f.label=b;f.$field=$(c);f.field=c;f.$label.data("InFieldLabels",f);f.showing=true;f.init=function(){f.options=$.extend({},$.InFieldLabels.defaultOptions,d);if(f.$field.val()!=""){f.$label.hide();f.showing=false};f.$field.focus(function(){f.fadeOnFocus()}).blur(function(){f.checkForEmpty(true)}).bind('keydown.infieldlabel',function(e){f.hideOnChange(e)}).change(function(e){f.checkForEmpty()}).bind('onPropertyChange',function(){f.checkForEmpty()})};f.fadeOnFocus=function(){if(f.showing){f.setOpacity(f.options.fadeOpacity)}};f.setOpacity=function(a){f.$label.stop().animate({opacity:a},f.options.fadeDuration);f.showing=(a>0.0)};f.checkForEmpty=function(a){if(f.$field.val()==""){f.prepForShow();f.setOpacity(a?1.0:f.options.fadeOpacity)}else{f.setOpacity(0.0)}};f.prepForShow=function(e){if(!f.showing){f.$label.css({opacity:0.0}).show();f.$field.bind('keydown.infieldlabel',function(e){f.hideOnChange(e)})}};f.hideOnChange=function(e){if((e.keyCode==16)||(e.keyCode==9))return;if(f.showing){f.$label.hide();f.showing=false};f.$field.unbind('keydown.infieldlabel')};f.init()};$.InFieldLabels.defaultOptions={fadeOpacity:0.5,fadeDuration:300};$.fn.inFieldLabels=function(c){return this.each(function(){var a=$(this).attr('for');if(!a)return;var b=$("input#"+a+"[type='text'],"+"input#"+a+"[type='password'],"+"textarea#"+a);if(b.length==0)return;(new $.InFieldLabels(this,b[0],c))})}})(jQuery);


/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.5
 * 
 * Changelog :
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
 


;(function($){

	$.fn.extend({
		selectbox: function(options) {
			return this.each(function() {
				new jQuery.SelectBox(this, options);
			});
		}
	});
	
	if (!window.console) {
		var console = {
			log: function(msg) { 
		 }
		}
	}

	$.SelectBox = function(selectobj, options) {
		
		var opt = options || {};
		opt.inputClass = opt.inputClass || "selectbox";
		opt.inputDefault = opt.inputDefault || "select-default";
		opt.inputHover = opt.inputHover || "select-over";
		opt.inputClick = opt.inputClick || "select-at";
		opt.containerClass = opt.containerClass || "selectbox-wrapper";
		opt.hoverClass = opt.hoverClass || "current";
		opt.currentClass = opt.selectedClass || "selected"
		opt.debug = opt.debug || false;
		
		var firstFocusEvent =false;
		var elm_id = selectobj.id;
		var active = -1;
		var inFocus = false;
		var hasfocus = 0;
		var $select = $(selectobj);
		var $container = setupContainer(opt);
		var $input = setupInput(opt);
		$select.hide().before($input).before($container);
		
		init();
		
		$input
		.mouseover(function() {
			$input.addClass(opt.inputHover);
		})
		.mouseout(function() {
			$input.removeClass(opt.inputHover);
		})
		
		.click(function(){
			if (!inFocus) {
				$container.toggle();
				$input.addClass(opt.inputClick);
			}
		})
		
		
		.focus(function(){
			if ($container.not(':visible')) {
				inFocus = true;
				$container.show();
				if ($input.hasClass(opt.inputHover)) {
					$input.removeClass(opt.inputHover);
				}
				$input.addClass(opt.inputClick);
			}
		})
	
		.keydown(function(event) {
			switch(event.keyCode) {
				case 38: // up
					event.preventDefault();
					moveSelect(-1);
					break;
				case 40: // down
					event.preventDefault();
					moveSelect(1);
					break;
				case 13: // return
					event.preventDefault(); // seems not working in mac !
					$('li.'+opt.hoverClass).trigger('click');
					break;
				case 27: //escape
				  hideMe();
				  break;
			}
		})
		
		.keypress(function(event) {
			switch(event.keyCode) {
				case 38: // up
					event.preventDefault();
					moveSelect(-1);
					break;
				case 40: // down
					event.preventDefault();
					moveSelect(1);
					break;
				case 13: // return
					event.preventDefault(); // seems not working in mac !
					$('li.'+opt.hoverClass).trigger('click');
					break;
				case 27: //escape
				  hideMe();
				  break;
			}
		})
		
		.blur(function() {
			if ($container.is(':visible') && hasfocus > 0 ) {
				if (opt.debug) console.log('container visible and has focus');
			} else {
				hideMe();
			}
		});
		
		function init() {
			$container.append(getSelectOptions($input.attr('id'))).hide();
		}
		
		function getSelectOptions(parentid) {
			var select_options = new Array();
			var ul = document.createElement('ul');
			$select.children('option').each(function() {
				var li = document.createElement('li');
				li.setAttribute('id', parentid + '_' + $(this).val());
				li.innerHTML = $(this).html();
				if ($(this).is(':selected')) {
					$input.val($(this).html());
					$(li).addClass(opt.currentClass);
				}
				if ($(this).is('option[value="0"]')) {
					$(li).addClass('notanoption');
				}
				ul.appendChild(li);
				$(li)
				.mouseover(function(event) {
					hasfocus = 1;
					jQuery(event.target, $container).addClass(opt.hoverClass);
				})
				.mouseout(function(event) {
					hasfocus = -1;
					jQuery(event.target, $container).removeClass(opt.hoverClass);
				})
				.click(function(event) {
					var fl = $('li.'+opt.hoverClass, $container).get(0);
					$('li.'+opt.currentClass).removeClass(opt.currentClass); 
					$(this).addClass(opt.currentClass);
					setCurrent();
					hideMe();
				});
			});
			return ul;
		}
	
		function hideMe() { 
			hasfocus = 0;
			$container.hide();
			if ($input.hasClass(opt.inputClick)) {
				$input.removeClass(opt.inputClick);
			}
		}
		
		function setupContainer(options) {
			var container = document.createElement("div");
			$container = $(container);
			$container.attr('id', elm_id+'_container');
			$container.addClass(opt.containerClass);
			return $container;
		}
		
		function setupInput(options) {
			var input = document.createElement("input");
			var $input = $(input);
			$input.attr("id", elm_id+"_input");
			$input.attr("type", "text");
			$input.addClass(opt.inputClass);
			$input.addClass(opt.inputDefault);
			$input.attr("autocomplete", "off");
			$input.attr("readonly", "readonly");
			$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
			return $input;	
		}
		
		function moveSelect(step) {
			var lis = $("li", $container);
			if (!lis) return;
			active += step;
			if (active < 0) {
				active = 0;
			} else if (active >= lis.size()) {
				active = lis.size() - 1;
			}
			lis.removeClass(opt.hoverClass);
			$(lis[active]).addClass(opt.hoverClass);
		}
		
		function setCurrent() {	
			var li = $("li."+opt.currentClass, $container).get(0);
			var el = li.id.replace('ins-type_input_', '');
			$select.val(el);
			$input.val($(li).html());
			if ($input.val() == $select.children('option[value="0"]').html()) {
				$input.addClass(opt.inputDefault);
			} else if ($input.hasClass(opt.inputDefault)) {
					$input.removeClass(opt.inputDefault);
			}
			return true;
		}
		
		// select value
		function getCurrentSelected() {
			return $select.val();
		}
		
		// input value
		function getCurrentValue() {
			return $input.val();
		}
		
	};
})(jQuery);
